java – 如何确保使用Spring @Configuration注释初始化相关配置?

前端之家收集整理的这篇文章主要介绍了java – 如何确保使用Spring @Configuration注释初始化相关配置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试使用@Configuration注释来连接我的应用程序,但我在其中一个初始化程序中不断获得NullPointerException,因为它引用的bean尚未初始化(我认为).我已经尝试在web.xml中指定’root’配置类,并尝试进行包扫描,似乎都不起作用.

抱歉,大代码转储.我试图生成一组更简单的类来重现这个问题,但当然,当我这样做时,一切都运行良好.这是我的课程(导入省略):

DataSourceConfig.java

@Configuration
public class DataSourceConfig {

    public DataSourceConfig() {
        System.err.println("DataSourceConfig constructed...");
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource bean = new BasicDataSource();
        bean.setDriverClassName("com.MysqL.jdbc.Driver");
        bean.setUrl("jdbc:MysqL://localhost:3306/observation");
        bean.setUsername("observation");
        bean.setPassword("*******");
        bean.setInitialSize(1);
        bean.setMaxActive(5);
        bean.setTestOnBorrow(true);
        System.err.println("dataSource bean initialized: " + bean.toString());
        return bean;
    }
}

HibernateConfig.java

@Configuration
@Import(DataSourceConfig.class)
public class HibernateConfig {

    public HibernateConfig() {
        System.err.println("HibernateConfig constructing...");
    }

    @Autowired
    private DataSourceConfig dataSourceConfig;

    @Bean
    protected NamingStrategy namingStrategy() {
        return new ImprovedNamingStrategy();
    }

    private AnnotationSessionfactorybean sessionfactorybean = null;

    @Bean
    @DependsOn("dataSourceConfig")
    public AnnotationSessionfactorybean sessionFactory() {
        if (sessionfactorybean == null) {
            sessionfactorybean = new AnnotationSessionfactorybean();
NPE Here--> sessionfactorybean.setDataSource(dataSourceConfig.dataSource()); 
            sessionfactorybean.setSchemaUpdate(true);
            sessionfactorybean.setNamingStrategy(namingStrategy());
            sessionfactorybean.setPackagesToScan(new String[] {
                    "com.newco.observations.domain","com.newco.observations.domain.*" });
            Properties props = new Properties();
            props.setProperty("hibernate.default_schema","observation");
            props.setProperty("hibernate.dialect","org.hibernate.dialect.MysqLDialect");
            props.setProperty("hibernate.show_sql","true");
            sessionfactorybean.setHibernateProperties(props);
            System.err.println("sessionFactory initialized");
        }
        return sessionfactorybean;
    }

    @Bean
    @DependsOn("dataSourceConfig")
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSourceConfig.dataSource());
    }

    @Bean
    @DependsOn("sessionFactory")
    public ResourceTransactionManager txManager() {
        HibernateTransactionManager bean = new HibernateTransactionManager();
        bean.setSessionFactory((SessionFactory) sessionFactory().getObject());
        return bean;
    }

    @Bean
    @DependsOn("sessionFactory")
    public HibernateTemplate hibernateTemplate() {
        return new HibernateTemplate((SessionFactory) sessionFactory()
                .getObject());
    }
}

DaoConfig.java:

@Configuration
@Import(HibernateConfig.class)
public class DaoConfig {

    public DaoConfig()
    {
        System.err.println("DaoConfig constructing...");
    }

    private @Autowired HibernateConfig hibernateConfig;

    @Bean
    @DependsOn("hibernateTemplate")
    public PhenomenonGroupDao phenomenonGroupDao()
    {
        PhenomenonGroupDaoImpl bean = new PhenomenonGroupDaoImpl();
        bean.setHibernateTemplate(hibernateConfig.hibernateTemplate());
        return bean;
    }

    @Bean
    @DependsOn("hibernateTemplate")
    public PhenomenonDao phenomenonDao()
    {
        PhenomenonDaoImpl bean = new PhenomenonDaoImpl();
        bean.setHibernateTemplate(hibernateConfig.hibernateTemplate());
        return bean;
    }

    @Bean
    @DependsOn("hibernateTemplate")
    public DiscretePhenomenonDao discretePhenomenonDao()
    {
        DiscretePhenomenonDaoImpl bean = new DiscretePhenomenonDaoImpl();
        bean.setHibernateTemplate(hibernateConfig.hibernateTemplate());
        return bean;
    }


}

您可以从System.err.println和@DependsOn注释中看到一种关于我正在做的事情.

我可以提供完整的日志,如果它有用,但这里是我认为相关的行(有一点格式化,使其更具可读性(可能)):

> 208 [Thread-0] INFO org.springframework.context.annotation.ConfigurationClassEnhancer
>成功增强了com.bjk.observation.server.config.DaoConfig;增强的类名是:com.bjk.observation.server.config.DaoConfig $$EnhancerByCGLIB $$96e1956
> 229 [Thread-0] INFO org.springframework.beans.factory.support.DefaultListablebeanfactory
>在org.springframework.beans.factory.support.DefaultListablebeanfactory@185572a中预先实例化单例:定义bean [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation .internalrequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,daoConfig,com.bjk.observation.server.config.DataSourceConfig#0,dataSource,com.bjk.observation.server.config .HibernateConfig#0,namingStrategy,sessionFactory,jdbcTemplate,txManager,hibernateTemplate,phenomenonGroupDao,phenomenonDao,discretePhenomenonDao];工厂层级DaoConfig构建的根…
> 252 [Thread-0] INFO org.springframework.beans.factory.support.DefaultListablebeanfactory
>在org.springframework.beans.factory.support.DefaultListablebeanfactory@185572a中销毁单身人士:定义bean [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalrequiredAnnotationProcessor,com.bjk.observation.server.config.HibernateConfig #0,discretePhenomenonDao];工厂层级的根
> 253 [Thread-0] ERROR org.springframework.web.context.ContextLoader
>上下文初始化失败org.springframework.beans.factory.BeanCreationException:创建名为’daoConfig’的bean时出错:注入自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.bjk.observation.server.config.HibernateConfig com.bjk.observation.server.config.DaoConfig.hibernateConfig;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为’com.bjk.observation.server.config.HibernateConfig#0’的bean时出错:bean的实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化bean类[com.bjk.observation.server.config.HibernateConfig]:构造函数抛出异常;嵌套异常是java.lang.NullPointerException

最佳答案
问题,我相信在这里:

@Autowired
private DataSourceConfig dataSourceConfig;

你不应该明确地将自己与其他@Configuration-annotated类联系起来,而是与它们产生的bean联系. Spring将为您挑选管道.

所以用更简单的方法替换上面的字段:

@Autowired
private DataSource dataSource;

Spring将从DataSourceConfig获取DataSource并将其透明地注入到字段中.

同样,替换

@Autowired 
private HibernateConfig hibernateConfig;

@Autowired 
private HibernateTemplate hibernateTemplate;

您会注意到@Configuration样式在使用像AnnotationSessionfactorybean这样的工厂bean时感觉不太好,因为您经常需要自己调用getObject().有时,使用XML配置更自然,并将其与java配置样式混合使用.

原文链接:https://www.f2er.com/spring/432271.html

猜你在找的Spring相关文章