Spring Boot 应用程序忽略 Java 配置。

3

我正在开发一个相对简单的Spring Boot应用程序,其中使用了几个Java配置类。然而,似乎并没有读取到配置信息。尽管我在各处设置了断点,但没有任何反应。我甚至抛出了一些RuntimeException来验证我的调试器是否有问题。

在我的主类中,我有标准的Spring Boot主方法:

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

如您所见,我使用了@ComponentScan@EnableAutoConfiguration标记它。应用程序类位于classpath的根目录下。我对@ComponentScan注解的理解是它将搜索其下方所有的配置类。

在下一层的一个包中,我有所有的配置类:

我的“公共”配置

@Configuration
@EnableJpaRepositories("com.codechimp.XXX.repository")
@EnableTransactionManagement
public class AppCommonConfig {
    @Inject
    private Environment environment;

    /* Define common beans here like datasource and such */
}

我的Spring Security配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Inject
    private LocalXXXUserDetailsService localXXXUserDetailsService;

        /**
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(HttpSecurity)
     */
    @Autowired
    protected void configure(HttpSecurity http) throws Exception {
        //  Configure http
    }

    /**
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configureGlobal(AuthenticationManagerBuilder)
     */
    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        // Configure auth
    }
}

然而,当我运行应用程序时,似乎没有调用这些配置类中的任何方法。就像它们完全被忽略了一样。正如我所说,我已经尝试设置断点,甚至在所有方法的开头抛出RuntimeException:

if (true)
    throw new RuntimeException("Break!");

诚然,我在使用Java配置方面没有太多经验,但我一次又一次地查看了文档,却没有发现缺失的部分。


你有解决这个问题的运气吗?我也遇到了同样的问题。我似乎无法理解为什么会选择配置。只有一些配置被选中,而另一些则没有。在我的情况下,类路径中有多个WebMvcConfigurerAdapter。 - Ashok Koyi
2个回答

1
我认为您需要将Application设置为@Configuration
从默认包执行@ComponentScan不是一个好主意(我猜这是您指的“类路径根目录”)。这会导致一些功能失效,严重的是它会扫描类路径上所有的jar包,这不是一个好主意(可能会导致应用程序崩溃)。

“根”是指我的应用程序类路径的公共根目录,例如com.xxx.yyy,其中所有代码类都按子包进行排序,如“domain”,“config”等。我同意从“默认”扫描会很糟糕,更不用说这是一种可怕的组织代码的方式了。我将尝试在我的“Application”类中添加@Configuration并报告结果。 - CodeChimp
我刚刚尝试将@Configuration添加到Application中,但似乎仍然没有加载配置类。还有其他想法吗? - CodeChimp
不行。你能把整个项目发布到某个地方吗? - Dave Syer

0

你需要添加

@SpringBootApplication

将此代码段添加到您的Spring Boot主类中。从文档中可以了解到:
/** * 表示一个{@link Configuration配置}类,声明一个或多个{@link Bean @Bean}方法, * 同时触发{@link EnableAutoConfiguration自动配置}和{@link ComponentScan组件扫描}。 * 这是一个方便的注释,相当于声明{@code @Configuration}, * {@code @EnableAutoConfiguration}和{@code @ComponentScan}。 * * @作者 Phillip Webb * @作者 Stephane Nicoll * @since 1.2.0 */

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接