Issue
I am setting up a project in Kotlin with Spring Security for login support. I am new to Spring Boot, so comments could be helpful. I have problem with Spring Boot not scanning my @Configuration
class and inject the @Bean
defined inside it. However, it recognized the same @Bean
inside the @SpringBootApplication
class.
I am not using WebSecurityConfigurerAdapter
because it is now deprecated.
Using logging.level.org.springframework=DEBUG
, I was able to confirm that spring boot recognized beans only when using @SpringBootApplication
. While using @Configuration
, it did NOT find it.
I don't want the bean to be there. I want to separate the bean into its own configuration file, in a subpackage, using the @Configuration
. How do I do that?
Here is a screenshot of the found bean when debugging, and the bean was defined in @SpringBootApplication
.
Here I have the different relevant class defintions:
Main class
@SpringBootApplication
class DemoApplication {
// @Bean // <--- this bean is recognized
// fun pilterChain(http: HttpSecurity): SecurityFilterChain {
// http.authorizeRequests().anyRequest().anonymous().and().formLogin().and().httpBasic()
// return http.build()
// }
}
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
Controller class
@RestController
class MessageResource {
@GetMapping
fun index(): String = "Hello World"
}
SecurityConfig.kt in subpackage
@Configuration
class SecurityConfig {
@Bean // <--- this bean is not recognized
fun pilterChain(http: HttpSecurity): SecurityFilterChain {
http.authorizeRequests().anyRequest().anonymous().and().formLogin().and().httpBasic()
return http.build()
}
}
Edit 1: Add project structure
Solution
This is because your SecurityConfig
is in a package that is not the same package of your DemoApplication
or a child package of the package of DemoApplication
.
To solve it move the package of SecurityConfig
to the package of DemoApplication
. It will then become a child package and should work.
Answered By - Daniel Jacob
Answer Checked By - Robin (JavaFixing Admin)