Источник данных бина находится на моей фабрике бинов, но я получил 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();
}
}
И я запускаю программу и получаю вывод, как показано ниже:
Exception in thread "main" java.lang.NullPointerException
at com.pain.DataSourceConfiguration.showDataSource(DataSourceConfiguration.java:40)
at com.pain.DataSourceTest.dataSourceDemo(DataSourceTest.java:23)
at com.pain.DataSourceTest.main(DataSourceTest.java:14)
[dataSourceConfiguration, org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.event.internalEventListenerProcessor, org.springframework.context.event.internalEventListenerFactory, org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration, org.springframework.transaction.config.internalTransactionAdvisor, TransactionsAttributeSource, TransactionsInterceptor, org.springframework.transaction.config.internalTransactionalEventListenerFactory, dataSource, TransactionsManager, org.springframework.aop.config.internalAutoProxyCreator]