我想在以下配置中将dataSource
bean注入我的sessionFactory
bean:
@Configuration
public class HibernateConfig {
@Bean(name="dataSource")
public javax.sql.DataSource getDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//set dataSource parameters from a .properties file
return dataSource;
}
@Bean(name="sessionFactory")
@Scope("singleton")
public FactoryBean<SessionFactory> getSessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
//How to reference/inject/autowire the dataSource bean declared above in the sessionFactory#dataSource property ??
return sessionFactory;
}
}
我怎么能实现这一目标?
答案 0 :(得分:1)
以下代码应该有效
@Configuration
public class HibernateConfig {
@Bean(name = "dataSource")
public javax.sql.DataSource getDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
return dataSource;
}
@Bean(name = "sessionFactory")
@Scope("singleton")
public FactoryBean<SessionFactory> getSessionFactory(javax.sql.DataSource dataSource){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory;
}
}
Spring提供了一种机制,我们可以使用@Bean方法参数传递这些bean依赖项。它们由框架注入,就像构造函数依赖项被解析一样。
答案 1 :(得分:1)
你可以通过几种方式做到这一点。我在下面简化了所有包含工作示例的案例。
方法#1 - 按类型自动注入
@Configuration
public class HibernateConfig {
@Bean
public A getMyA() {
return new A();
}
@Bean
public B getMyB(A a) {
System.out.println(a != null);
return new B();
}
}
class A {}
class B {}
方法#2 - 按类型显式注入
@Configuration
public class HibernateConfig {
@Bean
public A getMyA() {
return new A();
}
@Bean
@Autowired
public B getMyB(A a) {
System.out.println(a != null);
return new B();
}
}
class A {}
class B {}
方法#3 - 按名称注入 你正在尝试这个
@Configuration
public class HibernateConfig {
@Bean(name = "myOtherBeanName")
public A getMyA() {
return new A();
}
@Bean
@Autowired
public B getMyB(@Qualifier("myOtherBeanName") A a) {
System.out.println(a != null);
return new B();
}
}
class A {}
class B {}
方法#4 - 非注入/显式方法调用
@Configuration
public class HibernateConfig {
@Bean(name = "myOtherBeanName")
public A getMyA() {
return new A();
}
@Bean
public B getMyB() {
// call me as usual - getMyA()
return new B();
}
}
class A {}
class B {}
有很多方式它真正成为品味/偏好的问题。
以上所有内容都可以使用最小的Main类进行测试运行:
public class Main {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(HibernateConfig.class);
}
}