如果自动扫描类,Spring @Bean将自动装配

时间:2017-06-03 15:41:47

标签: spring spring-mvc spring-data

我读到了有关组件扫描的内容,据我所知,配置类是自动扫描的。我的问题是否有以下内容:

@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
        return new AuthenticationService();
    }
}

如果已经扫描了@Configuration(因此应用程序配置可用),那么它内部的bean不会被创建吗?我有点困惑,因为他们说@Bean没有自动扫描

1 个答案:

答案 0 :(得分:-1)

没有。 Spring不会扫描@Bean方法。

在这里,您正在创建AuthenticationService的bean,就像使用new关键字的任何其他Java程序一样。

AuthenticationService authenticationService = new AuthenticationService();

相同

如果您希望spring在AuthenticationService类中创建AppConfig的bean,请使用@Autowired注释

@Autowired
private AuthenticationService authenticationService;

希望这有帮助!

编辑:

@ M.Deinum纠正我,春天不会根据@Autowired注释创建bean。如果它们的类使用@ Component / @Configuration / @Service注释注释,那么它们将由spring自动创建。

@ M.Deinum,谢谢你。