Spring bean profile reference - spring

I started using bean profile for conditional bean creation, but When i use the profiled bean outside of profile with ref I get exception nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'pb' is defined
<bean id="q" class="com.Q"> //spring can not create this bean since it depends on `pb` bean which is profiled.
<property name="p" ref="pb"/>
</bean>
<beans profile="a">
<bean id="pb" class="com.T"/>
</beans>
<beans profile="b">
<bean id="pb" class="com.T"/>
</beans>
How can I achieve this? I am sure a profile is on:
System.setProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "a");
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "a");

Related

Unable to locate a ejb in spring context

I am trying to use a EJB singleton bean inside of spring bean but somehow it unable to locate a this ejb and getting a message when run a server:
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationFailureHandler' defined in class path resource [spring-security-config.xml]: Cannot resolve reference to bean 'loginAttemptService' while setting bean property 'loginAttemptService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loginAttemptService' is defined
Here is a EJB:
public interface ILoginAttemptService {
public boolean checkout(String username);
}
Here is implementation:
#Slf4j
#Stateless(name = "loginAttemptService")
#Singleton
public class LoginAttemptsService implements ILoginAttemptService {
..
}
In spring framework this is how i define a stateless bean:
<bean id="loginAttemptServiceBean"
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName"
value="java:app/osloproject-ejb/loginAttemptService"/>
<property name="businessInterface"
value="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
</bean>
<bean id="authSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="redirectStrategy">
<bean class="com.hospitality.hp.securitycommons.tools.spring.CORSCompatibleTwoFactorAuthenticationRedirectStrategy">
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
</property>
</bean>
<bean id="authenticationFailureHandler"
class="com.hospitality.hp.securitycommons.tools.spring.AuthenticationFailureCustomHandler">
<property name="useForward" value="true"/>
<property name="defaultFailureUrl" value="/login.jsp"/>
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
Can someone tell me why it unable to find the JNDI name of this EJB ?
try
<jee:local-slsb id="loginAttemptServiceBean" jndi-name="java:app/osloproject-ejb/loginAttemptService"
business-interface="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
"jee" is Spring’s namespace.and also check the jndi-name value is correct

JPA No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

I have a JPA/spring/hibernate application deployed on Tomcat 8. But when the tomcat server startup i can see this warning message "No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined". Help would be appreciated because i have no idea about the configuration error.
persistence.xml
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
...
spring context files are defined into several files for reusability
context-ds.xml
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
</bean>
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
...
context-config.xml
<context:annotation-config />
<context:component-scan base-package="com.app" />
<jpa:repositories base-package="com.app" />
<tx:annotation-driven transaction-manager="txManager"
order="200" />
and web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context-config.xml, /WEB-INF/context-ds.xml, /WEB-INF/context-dao.xml</param-value>
</context-param>
and DAO abstract class defines the PersistenceContext annotation
#PersistenceContext
protected EntityManager entityManager;
Real message
11:45:18.710 [localhost-startStop-1] WARN AbstractBeanFactory.getTypeForFactoryBean - Bean creation exception on FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDAO' defined in ServletContext resource [/WEB-INF/context-dao.xml]: Cannot create inner bean 'genericDao$child#632cb33' of type [com.app.dao.GenericDaoImpl] while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericDao$child#632cb33': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
if i declare PersistenceContext like this, i have the message No bean named 'persistenceUnit' is defined
#PersistenceContext(unitName="persistenceUnit")
protected EntityManager entityManager;
you have to define in an #Configuration annotated class a bean like this... a nd name it accordingly to your ref
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = null;
try {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabasePlatform(MyAppSettings.getDbPlattform());
HibernateJpaDialect jpd = new HibernateJpaDialect();
factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaDialect(jpd);
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(MyAppSettings.packagesToScan);
factory.setDataSource(MyDataSource());
} catch (SQLException e) {
e.printStackTrace();
}
return factory;
}
edit:
maybe your spring config xml isnt included into component scan
try :
#ImportResource("classpath:spring-config.xml")
....please post the full stacjtrace of you eception..

Combination of scope-proxy and parent

Hi I have the following short code :
https://github.com/shmuel-buchnik/scope-issue
I am getting the following error :
"Invalid property 'targetBeanName' of bean class [C]: Bean property 'targetBeanName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?"
I will be happy to understand way .
Thanks in advance.
Adding context file to save access to github
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean name="a" class="A">
<property name="action" ref="c"/>
</bean>
<bean name="b" class="B" scope="prototype">
<property name="d" ref="d"/>
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
<bean name="c" class="C" parent="b" scope="prototype">
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
<bean name="d" class="D"/>
</beans>
Well after debugging this is the issue :
When you define a parent in spring that means that you want to inherit parent bean configuration.
When you define scope proxy the proxy bean holds two properties targetBeanName and ProxyTargetClass.
When you inherit a bean that is a scoped proxy you get those properties as part of merging parent bean configuration .Then your bean try to find a setter for setting property and raise exception.
This means that in our example even if c was not scoped proxy we were still get the exception.
You cannot use a bean definition as a parent if the bean definition is configured as an <aop:scoped-proxy>.
Thus, just delete the <aop:scoped-proxy> declaration for the b bean, and it will work.

why autowired variable in prototype scope works only in the first instance

I am trying to Autowired RestTemplate and I am using the suggestion from why can I autowire or inject pojo but I can't autowire or inject RestTemplate . Unfortunetlly I am facing a problem from the second instantiation. The variable restTemplate works only once. After that, it is null. I guess that I might have done some mistake in dispatcher-servlet or web.xml config.
I know that the scope prototype creates a new instance every time it is called but I wasn't expect the auto wired RestTemplate to be null in the second instance. All others autowired variables runs perfectly every calls.
I saw some similiar threads and all of them ends up with some solution related to create a scope proxy. I changed to #Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) but I got the error "Can only specify arguments for the getBean method when referring to a prototype bean definition". Honestly I can't imagine this as the right direction for my case as I have problem only with restTemplate and in the second evoke of context.getBean.
//the process starts here
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
display = context.getBean(Lo_DisplayHandler.class, request, response);
display.lastPage();
DisplayHandler
#Component
#Scope("prototype")
public class Lo_DisplayHandler extends Lo_Handler {
//this constructor runs twice when the application start
public Lo_DisplayHandler() {
super();
}
this constructor runs every time the bean is get from context (context.getBean(Lo_DisplayHandler.class, request, response)). The first time Lo_DisplayHandler is created restTemplate is filled in but from the second time forward restTemplate is null
public Lo_DisplayHandler(HttpServletRequest request,HttpServletResponse response) {
super();
//get DB2 connection and set some data in session
}
#Autowired
private RestTemplate restTemplate;
//restTemplate will exist only in the first time
LogDisplay _l = restTemplate.postForObject(RestProperties.getUrl() + RestProperties.getFirstpage(),_mas60010, LogDisplay.class);
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.myCompany.mhe.common.controller, com.myCompany.mhe.log.handler, com.myCompany.mhe.utilities, com.myCompany.mhe.log.domain, com.myCompany.mhe.log.storedprocedure" />
<context:property-placeholder location="classpath:restServices.properties"/>
<mvc:resources mapping="/**" location="/" />
<!—-
If take the next three beans definition from here to applicationContext.xml and change contextConfigLocation to point to applicationContext.xml instead of mvc-dispatcher-servlet.xml my controller stops to work
-->
<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonObjectMapper" />
<property name="targetMethod" value="configure" />
<property name="arguments">
<list>
<value type="com.fasterxml.jackson.databind.DeserializationFeature">READ_DATE_TIMESTAMPS_AS_NANOSECONDS</value>
<value>true</value>
</list>
</property>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
</beans>
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
//Exception after default constructor removed
[WARNING ] Exception encountered during context initialization - cancelling refresh attempt
Error creating bean with name 'lo_Controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.mhe.Mhe_Handler com.mycompany.mhe.common.controller.Lo_Controller.mhe_Handler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lo_DisplayHandler' defined in file [C:\STS\wsRestTemplate\MHE_original\WebContent\WEB-INF\classes\com\mycompany\mhe\log\handler\Lo_DisplayHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mycompany.mhe.log.handler.Lo_DisplayHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mycompany.mhe.log.handler.Lo_DisplayHandler.<init>()
[ERROR ] Context initialization failed
Error creating bean with name 'lo_Controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.mhe.Mhe_Handler com.mycompany.mhe.common.controller.Lo_Controller.mhe_Handler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lo_DisplayHandler' defined in file [C:\STS\wsRestTemplate\MHE_original\WebContent\WEB-INF\classes\com\mycompany\mhe\log\handler\Lo_DisplayHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mycompany.mhe.log.handler.Lo_DisplayHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mycompany.mhe.log.handler.Lo_DisplayHandler.<init>()

Error Caused by: org.hibernate.HibernateException: Could not instantiate connection provider [org.connection.C3P0ConnectionProvider]

I have an error in Hibernate 4.1.2.FINAL, JBoss 7.1.1,and Spring 3.1.0.RELEASE,like this:
12:10:50,853 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-2)
Context initialization failed: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'departamentoDao' defined in URL [vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]:Cannot resolve reference to bean 'hibernateTemplate' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'hibernateTemplate' defined in URL [vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]:
Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in URL [vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]:
Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE]
Caused by:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'hibernateTemplate' defined in URL
[vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]:
Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in URL
[vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]:
Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE]
and :
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in URL [vfs:/opt/jboss-as-7.1.1.Final/standalone/deployments/projvehimerc.war/WEB-INF/classes/META-INF/spring/spring-hibernate.xml]: Invocation of init method failed; nestwared exception is org.hibernate.service.spi.ServiceException:
Unable to create requested service [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
>>Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service
>>Caused by: org.hibernate.HibernateException: Could not instantiate connection provider [org.connection.C3P0ConnectionProvider]
and my spring-hibernate configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Hibernate SessionFactory -->
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="vehicDataSource">
<!-- p:lobHandler-ref="defaultLobHandler"-->
<property name="annotatedClasses">
<list>
<!-- Procedimientos -->
<value>com.reglamb.projvehimerc.domain.HabilitacionVehicular_Inscripcion</value>
<!-- Main Properties -->
<value>com.reglamb.projvehimerc.domain.Transportista</value>
<value>com.reglamb.projvehimerc.domain.Ubigeo</value>
<value>com.reglamb.projvehimerc.domain.TransportistaNatural</value>
<value>com.reglamb.projvehimerc.domain.TransportistaJuridico</value>
<value>com.reglamb.projvehimerc.domain.Conductor</value>
<!-- Transportista's Ubigeo -->
<value>com.reglamb.projvehimerc.domain.ubigeo.Departamento</value>
<value>com.reglamb.projvehimerc.domain.ubigeo.Distrito</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
hibernate.default_schema=${hibernate.default_schema}
hibernate.jdbc.batch_size=${hibernate.jdbc.batch_size}
hibernate.c3p0.max_size=${hibernate.c3p0.max_size}
hibernate.c3p0.min_size=${hibernate.c3p0.min_size}
hibernate.c3p0.timeout=${hibernate.c3p0.timeout}
hibernate.c3p0.max_statements=${hibernate.c3p0.max_statements}
hibernate.c3p0.idle_test_period=${hibernate.c3p0.idle_test_period}
hibernate.c3p0.acquire_increment=${hibernate.c3p0.acquire_increment}
<!--hibernate.c3p0.validate=${hibernate.c3p0.validate}-->
<!--hibernate.cache.provider_class=${hibernate.cache.provider_class}-->
hibernate.connection.provider_class=${hibernate.connection.provider_class}
hibernate.show_sql=${hibernate.show_sql}
hibernate.hbm2ddl.auto=${hibernate.hbm2ddl.auto}
hibernate.id.new_generator_mappings=${hibernate.id.new_generator_mappings}
<!-- Auto Generated Schemas and tables not good for production
hibernate.hbm2ddl.auto=update-->
<!--hibernate.cache.use_second_level_cache=true-->
<!--hibernate.cache.use_query_cache=true-->
</value>
</property>
</bean>
<!-- Transaction Config -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<!-- Hibernate Template -->
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate"
p:sessionFactory-ref ="sessionFactory"/>
<!-- Injectores Procedimiento -->
<bean id="inscriptransportistaDao"
class="com.reglamb.projvehimerc.dao.hibernate.HabilitacionVehicular_InscripcionDaoHibernate" >
<property name="hibernateTemplate" ref ="hibernateTemplate" />
</bean>
<!-- Injectores Ubigeo -->
<bean id="ubigeoDao"
class="com.reglamb.projvehimerc.dao.hibernate.UbigeoDaoHibernate" >
<property name="hibernateTemplate" ref ="hibernateTemplate" />
</bean>
<bean id="departamentoDao"
class="com.reglamb.projvehimerc.dao.hibernate.ubigeo.DepartamentoDaoHibernate" >
<property name="hibernateTemplate" ref ="hibernateTemplate" />
</bean>
<bean id="distritoDao"
class="com.reglamb.projvehimerc.dao.hibernate.ubigeo.DistritoDaoHibernate" >
<property name="hibernateTemplate" ref ="hibernateTemplate" />
</bean><
<bean name="inscripcionHabilitacionVehicFacade" class="com.reglamb.projvehimerc.service.HabilitacionVehicular_InscripcionFacadeImpl" />
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
What's the error ? thnks.
It looks like you set hibernate.connection.provider_class to org.connection.C3P0ConnectionProvider.
It should be org.hibernate.connection.C3P0ConnectionProvider instead.

Resources