【问题标题】:Spring annotation @Required not working (no xml used)Spring注解@Required不起作用(没有使用xml)
【发布时间】:2020-02-13 16:47:33
【问题描述】:

我已经看到,当我将 @Required 放入 College.java 时,我没有收到异常并且代码运行良好。这不是预期的行为。请帮帮我。

@Component
public class College {


    public String s;

    @Required
    public void setS(String s) {
        this.s = s;
    }




@Configuration
public class ApplicationConfig {

    @Bean
    public College collegeBean()
    {
        return new College();
    } 

    @Bean
    public Principal principalBean()
    {
        return new Principal();
    } 

}

主要方法:

public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
    System.out.println("file loaded");
    College coll = context.getBean("collegeBean",College.class);
    System.out.println(coll.toString());
}

【问题讨论】:

  • 您使用的是哪个春季版本? @Required 自 5.1 起已弃用
  • 我正在使用的4.2版本

标签: spring annotations


【解决方案1】:

为什么@Required注解不起作用详细here

要使您的应用程序正常工作,您需要使用@ComponentScan 注释@Configuration 类。如果要自动检测的 bean 不在 @ComponentScan 的默认范围内,则需要相应地使用属性。

@Configuration
@ComponentScan
public class ApplicationConfig {..}

注意事项

  1. College 类已经用 @Component 注释,@ComponentScan 将检测 bean。你不需要ApplicationConfig 中的方法collegeBean()
  2. String bean 必须可用以支持依赖项。您也可以在 ApplicationConfig 中声明一个 bean。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 2013-05-22
    • 2019-06-04
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2016-12-03
    • 2012-05-01
    相关资源
    最近更新 更多