bean 数据源在我的 bean 工厂中,但是当我尝试访问数据源的方法时,我得到了 NPE。似乎@Autowired注释不起作用
@Configuration
@EnableTransactionManagement
public class DataSourceConfiguration {
@Autowired
private DataSource dataSource;
public static void main(String[] args) throws SQLException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
showBeans(context);
dataSourceDemo();
}
private static void showBeans(ApplicationContext context) {
System.out.println(Arrays.toString(context.getBeanDefinitionNames()));
}
private static void dataSourceDemo() throws SQLException {
DataSourceConfiguration demo = new DataSourceConfiguration();
demo.showDataSource();
}
@Bean(destroyMethod = "close")
public DataSource dataSource() throws Exception {
Properties properties = new Properties();
properties.setProperty("driverClassName", "com.mysql.jdbc.Driver");
properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/orange?characterEncoding=utf-8");
properties.setProperty("username", "mysql");
properties.setProperty("password", "123456");
return BasicDataSourceFactory.createDataSource(properties);
}
@Bean
public PlatformTransactionManager transactionManager() throws Exception {
return new DataSourceTransactionManager(dataSource());
// return new DataSourceTransactionManager(dataSource);
}
public void showDataSource() throws SQLException {
System.out.println("dataSource: " + dataSource.toString());
Connection connection = dataSource.getConnection();
System.out.println("connection: " + connection.toString());
connection.close();
}
}
阿波罗的战车
天涯尽头无女友
相关分类