代码之家  ›  专栏  ›  技术社区  ›  We are Borg

Spring、Spring MVC:将XML配置迁移到Java,使数据源未发现错误

  •  0
  • We are Borg  · 技术社区  · 6 年前

    我正在致力于将Spring XML XML配置移植到Java配置中。我们有很多使用xml的配置,如locale、cache、multi-part、spring-security。到目前为止,Spring安全配置不需要是Java,而是主要是RooTo.ExtEx.xml和Servel-CutExt.xml。在检查了其他用户的配置之后,我自己添加了一些配置,但是在迁移过程中遇到了一些问题。

    一个主要问题是我们在XML配置中使用了两个SessionFactory实例,每个实例都有特定的用途,这些实例在DAO层中被引用。我也希望用Java配置来维护它。谢谢您。

    错误:

    Caused by: 
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:704)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    

    webconfig.java:

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = {"com.ourapp.spring"})
    @EnableTransactionManagement
    @EnableCaching
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        }
    
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        }
    
        @Bean
        public ReloadableResourceBundleMessageSource messageSource(){
            ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
            messageSource.setBasename("../resources/locale/messages.properties");
            messageSource.setDefaultEncoding("UTF-8");
            return messageSource;
        }
    
        @Bean
        public LocaleChangeInterceptor localeInterceptor(){
            LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
            interceptor.setParamName("lang");
            return interceptor;
        }
    
        @Bean
        public MappingJackson2HttpMessageConverter converter() {
            return new MappingJackson2HttpMessageConverter();
        }
    
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/css/**").addResourceLocations("/css/");
            registry.addResourceHandler("/img/**").addResourceLocations("/img/");
            registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        }
    
        @Bean
        public InternalResourceViewResolver getInternalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("../webapp/WEB-INF/views/jsp/");
            resolver.setSuffix(".jsp");
            return resolver;
        }
    
        @Bean
        public DoNotTruncateMyUrls doNotTruncate(){
           return new DoNotTruncateMyUrls();
        }
    
        @Bean
        public MultipartResolver multipartResolver() {
            return new StandardServletMultipartResolver();
        }
    
        @Bean
        public DataSource getNormalDataSource(){
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:postgresql://localhost:PORT/DB_NAME");
            config.setUsername("USERNAME");
            config.setPassword("PASSWORD");
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            return new HikariDataSource(config);
        }
    
        @Bean(name = "sessionFactory_origin")
        public DataSource getSecondaryDataSource(){
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:postgresql://localhost:PORT/DB_NAME");
            config.setUsername("USERNAME");
            config.setPassword("PASSWORD");
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            return new HikariDataSource(config);
        }
    
    }
    

    appinitializer.java:

    public class AppInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext container) throws ServletException {
    
            AnnotationConfigWebApplicationContext context = new
                    AnnotationConfigWebApplicationContext();
            context.register(WebConfig.class);
            container.addListener(new ContextLoaderListener(context));
            context.setServletContext(container);
            ServletRegistration.Dynamic servlet = container.addServlet("dispatcher",
                    new DispatcherServlet(context));
            servlet.setLoadOnStartup(1);
            servlet.addMapping("*.");
        }
    }
    

    根上下文.xml:

    <beans:bean id="hibernate4AnnotatedSessionFactory_extended"
                    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <beans:property name="dataSource" ref="extended_transactions_data_source"/>
            <beans:property name="packagesToScan" value="com.ourapp.spring.model"/>
            <beans:property name="hibernateProperties">
                <beans:props>
                    <beans:prop key="hibernate.dialect">org.hibernate.dialect.USERNAMEQL9Dialect</beans:prop>
                    <beans:prop key="hibernate.show_sql">false</beans:prop>
                    <beans:prop key="hibernate.jdbc.batch_size">50</beans:prop>
                    <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
                    <beans:prop key="cache.use_second_level_cache">true</beans:prop>
                    <beans:prop key="cache.use_query_cache">true</beans:prop>
                    <beans:prop key="hibernate.order_updates">true</beans:prop>
                    <beans:prop key="show_sql">false</beans:prop>
                    <beans:prop key="connection.release_mode">after_statement</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>-->
    
    
         <!-- <beans:bean id="extended_transactions_data_source" class="com.zaxxer.hikari.HikariDataSource"  destroy-method="close">
            <beans:property name="dataSourceClassName" value="org.USERNAMEql.ds.PGSimpleDataSource"/>
            <beans:property name="maximumPoolSize" value="5" />
            <beans:property name="maxLifetime" value="0" />
            <beans:property name="idleTimeout" value="0" />
            <beans:property name="connectionTimeout" value="0"/>
            <beans:property name="dataSourceProperties">
                <beans:props>
                    <beans:prop key="url">jdbc:USERNAMEql://localhost:5432/DB_NAME</beans:prop>
                    <beans:prop key="user">USERNAME</beans:prop>
                    <beans:prop key="password">PASSWORD</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>
    
    
        <tx:annotation-driven transaction-manager="transactionManager_extended"/>
    
        <beans:bean id="transactionManager_extended" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <beans:property name="sessionFactory" ref="sessionFactory_extended"/>
        </beans:bean>
    
    
        <beans:bean id="sessionFactory_extended" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <beans:property name="dataSource" ref="extended_transactions_data_source" />
            <beans:property name="packagesToScan" value="com.ourapp.spring.model"/>
            <beans:property name="hibernateProperties">
                <beans:props>
                    <beans:prop key="hibernate.dialect">org.hibernate.dialect.USERNAMEQL9Dialect</beans:prop>
                    <beans:prop key="hibernate.show_sql">false</beans:prop>
                    <beans:prop key="hibernate.jdbc.batch_size">50</beans:prop>
                    <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
                    <beans:prop key="cache.use_second_level_cache">true</beans:prop>
                    <beans:prop key="cache.use_query_cache">true</beans:prop>
                    <beans:prop key="hibernate.order_updates">true</beans:prop>
                    <beans:prop key="show_sql">false</beans:prop>
                    <beans:prop key="connection.release_mode">after_statement</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>-->
    

    示例daoimpl:

    @Repository
    @Transactional
    public class RepliesDAOImpl implements RepliesDAO {
    
        @Autowired
        @Qualifier(value = "sessionFactory_origin")
        private final SessionFactory sessionFactory;
        @Autowired
        @Qualifier(value = "sessionFactory_extended")
        private final SessionFactory sessionFactory_extended;
        @Autowired
        public RepliesDAOImpl(@Qualifier("sessionFactory_origin") SessionFactory sessionFactory, @Qualifier("sessionFactory_extended") SessionFactory sessionFactory_extended) {
            this.sessionFactory = sessionFactory;
            this.sessionFactory_extended = sessionFactory_extended;
        }
    //Methods in the class
    }
    

    我还在pastebin中添加了整个配置 root-context.xml

    servlet-context.xml

    更新回复daoimpl

    @Repository
    @Transactional
    public class RepliesDAOImpl implements RepliesDAO {
    
        @Autowired
        @Qualifier(value = "dataSource")
        private DataSource dataSource;
    
        @Bean()
        @Qualifier("sessionFactory_origin")
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setPackagesToScan(
                    new String[] { "com.ourapp.spring" });
            return sessionFactory;
        }
    
    
     @Override
        public Long addReply(Replies replies, int conversationId, Person person) {
            SessionFactory sessi = (SessionFactory) sessionFactory();
            Session session = this.sessionFactory.getCurrentSession();
    }
        @Autowired
        @Qualifier(value = "sessionFactory_origin")
        private final SessionFactory sessionFactory;
    
        @Autowired
        @Qualifier(value = "sessionFactory_extended")
        private final SessionFactory sessionFactory_extended;
        @Autowired
        public RepliesDAOImpl(@Qualifier("sessionFactory_origin") SessionFactory sessionFactory, @Qualifier("sessionFactory_extended") SessionFactory sessionFactory_extended) {
            this.sessionFactory = sessionFactory;
            this.sessionFactory_extended = sessionFactory_extended;
        }
    

    更新的webconfig

    @Bean(name = "sessionFactory_origin")
        @Qualifier("dataSource")
        public DataSource getNormalDataSource(){
       // Bean definition
    }
    
     @Qualifier("extended_data_source")
        @Bean(name ="extended_dataSource" )
        public DataSource getSecondaryDataSource(){
    //Secondary data source
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Yati Sawhney    6 年前

    你错过了 @Qualifier(value = "sessionFactory_extended") 创建bean时 getNormalDataSource

    您需要提供一个自定义限定符,以便spring能够区分两个数据源

    如果您使用的是Spring4.something或“>”版本,则可以在创建bean和按如下方式注入bean时添加限定符:

    @Bean
    @Qualifier("<some-value-1>")
    public DataSource getNormalDataSource(){
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:postgresql://localhost:PORT/DB_NAME");
            config.setUsername("USERNAME");
            config.setPassword("PASSWORD");
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            return new HikariDataSource(config);
        }
    
    
    
    @Bean(name = "sessionFactory_origin")
    @Qualifier("<some-value-2>")
    public DataSource getSecondaryDataSource(){
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:postgresql://localhost:PORT/DB_NAME");
            config.setUsername("USERNAME");
            config.setPassword("PASSWORD");
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            return new HikariDataSource(config);
        }
    

    在注入时,还必须指定限定符

    @Autowired @Qualifier("<some-value-1>") private DataSource dataSource;
    

    您正在尝试将数据源注入sessionfactory。

    以下是您需要进行的更改:

     // If present in same file 
    
        @Bean()
    @Qualifier("sessionFactory_origin")
       public LocalSessionFactoryBean sessionFactory() {
          LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
          sessionFactory.setDataSource(getNormalDataSource());
          sessionFactory.setPackagesToScan(
            new String[] { "<packages>" });
          //If presenst
          sessionFactory.setHibernateProperties(hibernateProperties());
    
          return sessionFactory;
       }
    

    如果您使用这些bean是根据环境选择的。我建议你去看看 Profiles Conditional 肛门。