[英]Spring Configuration creating two beans instead of one
我正在使用Java配置使用Spring MVC编写RESTful Web服务。 我的配置文件如下。 我的问题是-我发现正在创建2个“ myService” bean实例,而不仅仅是一个实例。 我不确定为什么吗? 如何调整配置以仅创建一个?
谁能指出我正确的方向? 谢谢!
这是我的配置类。
@Configuration
public class MyConfig {
@Bean(name = "dataSource")
public DriverManagerDataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// datasource set up
return dataSource;
}
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DriverManagerDataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("com.mypackages");
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.enable_lazy_load_no_trans", "true");
properties.put("hibernate.id.new_generator_mappings", "true");
return properties;
}
@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
@Bean
public MyMainBean MyMainBean() {
MyMainBean bean = new MyMainBean();
bean.setService(myService());
bean.setValidator(myValidator());
return bean;
}
@Bean(name = "myService")
public MyService myService() {
MyService s = new MyService();
s.setDao1(myDao1());
s.setDao2(myDao2());
s.setCopyUtil(copyUtil());
return s;
}
@Bean
public MyDao1 myDao1() {
return new MyDao1();
}
@Bean
public MyDao2 myDao2() {
return new MyDao2();
}
@Bean
public CopyUtil copyUtil() {
return new CopyUtil();
}
@Bean
public ReportValidator reportValidator() {
ReportValidator validator = new ReportValidator();
validator.setService(myService());
return validator;
}
@Bean
public XMLValidator xmlValidator() {
XMLValidator validator = new XMLValidator();
validator.setService(myService());
return validator;
}
}
实际上,Spring在连接bean时很聪明,应该只调用一次 myService()
函数,然后将结果传递给其他myService()
调用,从而仅产生一个 MyService
bean。
确保确实获得了2个MyService
实例,例如,通过在MyService
类的构造函数中添加日志。
如果确实看到多个构造函数日志语句,请确保未在其他@Configuration
类中声明其他MyService
Bean,或者确保未在MyService
类上使用任何组件注释(即,不要使用@Service
, @Component
@Repository
)。
如果使用@Service
声明该类,它将有效地实例化该类并将其添加到上下文中。 当您再次使用@Bean
声明它时, 您将得到2个实例 ,因此请不要混合使用它们。
另外,您无需在此处使用这些@Autowired
注释,甚至无需调用其他bean,因为以下操作也将起作用:
@Configuration
public class DbConfiguration {
@Bean
public MovieDao dao() {
return new MovieDao();
}
@Bean
public MovieService service(MovieDao dao) {
return new MovieService(dao);
}
}
Spring将看到您需要一个MovieDao
来构建MovieService
,它将首先实例化dao并将其传递给服务bean。 您甚至不需要在类中添加@Service
或类似的注释!
真的很好,希望这些技巧对您有帮助;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.