简体   繁体   中英

Bean is in applicationContext but @Autowired annotation not working

The bean datasource is in my bean factory, but I got NPE when I tried to access datasource's method. Is seems like @Autowired annotation does not work

@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();
    }


}

And I exec the program and get output like following:

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, transactionAttributeSource, transactionInterceptor, org.springframework.transaction.config.internalTransactionalEventListenerFactory, dataSource, transactionManager, org.springframework.aop.config.internalAutoProxyCreator]

Your problem lies here:

DataSourceConfiguration demo = new DataSourceConfiguration();

You're creating an object manually without using spring's AOP. This way DataSourceConfiguration is not getting wrapped in proxy and dependency management fails.

To solve this, you would have to @Autowire it elsewhere, outside static context.

To amplify, having your program driver inside the @Configuration class and manually instantiating that class seems super wrong!

Your configuration class should have mainly configure beans and so should look like this:

@Configuration
@EnableTransactionManagement
public class DataSourceConfiguration {

    @Autowired
    private DataSource dataSource;

    @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());
    }
}

If you you are using plain spring then you can accomplish what you want, showing info about your data source, doing something like the following. Using spring as a service locator this way is pretty unidiomatic, and maybe even an anti-pattern):

public class MainCaller {

    public static void main(String[] args) {

       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
       DataSource ds = (DataSource)applicationContext.getBean("DataSource");
       showDataSource(ds);

    }
     public static void showDataSource(Datasource dataSource) throws SQLException {
        System.out.println("dataSource: " + dataSource.toString());
        Connection connection = dataSource.getConnection();
        System.out.println("connection: " + connection.toString());
        connection.close();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM