在spring boot项目中,有没有办法在@Bean方法中使用注入对象。在我的示例中,isdatasourceUse()
方法能够访问注入的数据源(来自dev或war配置文件)
@EnableScheduling
@Configuration
@EnableAspectJAutoProxy
@Profile({ "dev", "war" })
public class AppConfig {
Logger logger = LoggerFactory.getLogger(AppConfig.class);
@Autowired
DBPropertyBean dbPropertyBean;
@Bean(destroyMethod = "")
@Profile("war")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName(dbPropertyBean.getJndiName());
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
@Bean(destroyMethod = "close")
@Profile("dev")
public DataSource getDataSource() throws Exception {
com.mchange.v2.c3p0.ComboPooledDataSource ds = new com.mchange.v2.c3p0.ComboPooledDataSource();
ds.setUser(dbPropertyBean.getDsUsername());
ds.setPassword(dbPropertyBean.getDsPassword());
ds.setJdbcUrl(dbPropertyBean.getDsJdbcUrl());
ds.setDriverClass(dbPropertyBean.getDsDriverClass());
ds.setMaxPoolSize(dbPropertyBean.getDsMaxPoolSize());
ds.setMinPoolSize(dbPropertyBean.getDsMinPoolSize());
ds.setInitialPoolSize(dbPropertyBean.getDsInitPoolSize());
ds.setAcquireIncrement(dbPropertyBean.getDsAcquireInc());
ds.setAcquireRetryAttempts(dbPropertyBean.getDsAcquireRetryAtt());
ds.setPreferredTestQuery(dbPropertyBean.getPreferredTestQuery());
ds.setIdleConnectionTestPeriod(dbPropertyBean.getIdleConnectionTestPeriod());
return ds;
}
@Bean
public void datasourceUse() {
//How to user datasource here
}
}
答案 0 :(得分:0)
使用如下:
@Autowired
public void datasourceUse(DataSource dataSource) {
System.out.println(dataSource);
}