gpt4 book ai didi

java - Spring , Spring MVC : Migrate XML configuration to Java giving data source not found error

转载 作者:行者123 更新时间:2023-12-02 11:06:41 26 4
gpt4 key购买 nike

我正在致力于将 Spring-MVC XML 配置迁移到 Java 配置。我们有很多使用 XML 的配置,例如区域设置、缓存、多部分、spring-security。截至目前,Spring-security 配置不需要使用 Java,但主要是 root-context.xml 和 servlet-context.xml。在完成其他用户的配置后,我自己添加了一些配置,但在迁移过程中遇到了一些问题。

一个主要问题是我们在 XML 配置中使用 2 个 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
}

最佳答案

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

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

如果您使用的是 Spring 4.something 或“>”版本,您可以在创建 bean 和注入(inject)它们时添加限定符,如下所示:

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

在注入(inject)时,您还必须指定限定符

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

您正在尝试将 DataSource 注入(inject) 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,要根据环境来选择。我建议您访问ProfilesConditional注释。

关于java - Spring , Spring MVC : Migrate XML configuration to Java giving data source not found error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com