Spring注释@Required不起作用(未使用xml)
我已经看到,当我将@Required放在College.java中时,没有出现异常,代码运行良好。这不是预期的行为。请帮帮我Spring注释@Required不起作用(未使用xml),spring,annotations,Spring,Annotations,我已经看到,当我将@Required放在College.java中时,没有出现异常,代码运行良好。这不是预期的行为。请帮帮我 @Component public class College { public String s; @Required public void setS(String s) { this.s = s; } @Configuration public class ApplicationConfig {
@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
注释不起作用的原因
要使应用程序正常工作,需要使用@ComponentScan
注释@Configuration
类。如果要自动检测的bean不在的默认范围内,则需要相应地使用属性
@Configuration
@ComponentScan
public class ApplicationConfig {..}
注释
College
类已经用@Component
注释,@ComponentScan
将检测bean。在ApplicationConfig
String
bean来满足依赖关系。您可以在ApplicationConfig
中声明一个bean希望这有帮助。您使用的是哪种spring版本?从我正在使用的5.14.2版本起已弃用