Я работаю над проектом, который содержит два источника данных. Если я хочу ввести securityDataSource, Spring вместо этого добавляет вместо этого defaultDataSource.Конфигурация нескольких datasource
applicationContext.xml:
<bean id="defaultDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>${default.jndi.datasource.name}</value>
</property>
</bean>
<bean id="securityDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>${security.jndi.datasource.name}</value>
</property>
</bean>
сеттер:
@Required
@Resource
public void setSecurityDataSource(DataSource securityDataSource) {
jdbcTemplate = new JdbcTemplate(securityDataSource);
}
Сервер журналы это (который по-видимому, ничего не блокирует, хотя) и для безопасности и по умолчанию источника данных:
10:28:23.912 [INFO ] o.s.w.c.s.XmlWebApplicationContext - Bean 'defaultDataSource' of type [class org.springframework.jndi.JndiObjectFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
10:28:24.345 [INFO ] o.s.w.c.s.XmlWebApplicationContext - Bean 'defaultDataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
10:28:24.922 [INFO ] o.s.w.c.s.XmlWebApplicationContext - Bean 'securityDataSource' of type [class org.springframework.jndi.JndiObjectFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
10:28:25.444 [INFO ] o.s.w.c.s.XmlWebApplicationContext - Bean 'securityDataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Внутри кода не отображается ни один стек.
Когда я пытаюсь:
private SecurityUserDTO retrieve(String userLogin) {
return jdbcTemplate.query("SELECT * FROM users WHERE username = ?", with(userLogin), new UserExtractor());
}
Hibernate не найти пользователей таблицы, хранящиеся в базе данных безопасности, поскольку она ищет его в базе данных по умолчанию (который не имеет такой таблицы)
HTTP Status 401 - PreparedStatementCallback; bad SQL grammar [SELECT * FROM users WHERE username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'condor.users' doesn't exist
если я пытаюсь инъекционным и предоставления имени securityDataSource:
@Required
@Resource(name="securityDataSource")
public void setSecurityDataSource(DataSource securityDataSource) {
jdbcTemplate = new JdbcTemplate(securityDataSource);
}
я получу StackTrace:
12:17:48.557 [ERROR] o.s.w.c.ContextLoader - Context initialization failed
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'securityDataSource' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442) ~[spring-context-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416) ~[spring-context-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:549) ~[spring-context-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:159) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303) ~[spring-context-3.1.1.RELEASE.jar:3.1.1.RELEASE]
Wrapped by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'securityDataSource' is defined
Однако боб securityDataSource действительно существует, и инстанциирован весной в контексте.
помогите мне, пожалуйста, спасибо!
Убедитесь, что во время выполнения у вас есть только один контекст весны (и поэтому все ваши бобы идут к нему). Проблема может заключаться в том, что у вас несколько контекстов. Ваши источники данных объявляются в одном и вводятся в другом. Пример ситуации, когда у вас есть два контекста: если вы используете Spring MVC, у вас обычно есть один контекст для компонентов приложения (сервисы, DAO и т. Д.), А другой для Spring MVC-контроллеров. –
Любая идея, почему вы видите две записи с предупреждением «BeanPostProcessors»? Я бы ожидал увидеть только строку JndiObjectFactoryBean, а не строки BasicDataSource. Кроме того, вы можете заставить приложение работать только с одной из записей, но не с обоими? – enl8enmentnow