How to make Spring perform real JNDI lookup if the lookup attribute is present in Resource annotation - spring

We'd like to test EJB-s in unit tests as Spring components.
The one of the EJB-s using the Resources annotation in order to look up a JNDI values like this:
#Resource(lookup = "java:global/myapp/portal/url")
private String portalUrl;
The problem is that it seems that Spring tries to look up the value by type i.e. it looks for a bean of type java.lang.String in the application context instead of using JNDI.
Here's our code.
1st context:
<bean id="serverMock" class="myapp.JndiServerMock">
</bean>
2nd context:
<context:annotation-config />
<context:component-scan base-package="myapp">
<context:include-filter type="annotation" expression="javax.ejb.Stateless" />
<context:include-filter type="annotation"
expression="javax.annotation.Resources" />
</context:component-scan>
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
<property name="alwaysUseJndiLookup" value="true" />
</bean>
<bean id="clientMock" class="myapp.JndiClientMock">
<bean id="java:global/myapp/portal/url" class="java.lang.String">
<constructor-arg value="http://localhost:8080" type="java.lang.String"/>
</bean>
JndiServerMock:
public class JndiServerMock {
public JndiServerMock() throws IllegalStateException, NamingException {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind("java:global/myapp/portal/url", "http://localhost:8080");
builder.activate();
}
}
JndiClientMock:
public class JndiClientMock {
public JndiClientMock() throws NamingException {
Hashtable<String, String> prop = new Hashtable<String, String>();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.springframework.mock.jndi.SimpleNamingContextBuilder");
InitialContext ic = new InitialContext(prop);
System.err.println("result = " + ic.lookup("java:global/myapp/portal/url"));
}
}
ExampleBean:
#Stateless
public class ExampleBean {
#Resource(lookup = "java:global/myapp/portal/url")
private String portalUrl;
public ExampleBean() {
System.err.println("portalUrl = " + portalUrl);
}
}
public class MainApp {
public static void main(String[] args) {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.springframework.mock.jndi.SimpleNamingContextBuilder");
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("/spring/firstContext.xml",
"/spring/secondContext.xml");
ExampleBean exampleBean = applicationContext.getBean(ExampleBean.class);
}
}
If the "java:global/myapp/portal/url" bean definition is omitted then the following exception will be thrown:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=java:global/myapp/portal/url, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:457)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
... 13 more

I think the problem here is how you're trying to set the JNDI entry in the Spring config - here's an example of how to do this. This provides examples of other ways of achieving the same thing. However, if you're looking to do this for a unit test, I think the JUnit section here is likely to be a neater approach, but it certainly looks like you have lots of options!

Related

org.springframework.beans.factory.BeanCreationException: Could not autowire field:

I have problems with:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hdx.ssm.service.ItemsService com.hdx.ssm.controller.ItemsController.itemsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hdx.ssm.service.ItemsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is ItemsController:
#Controller
#RequestMapping("/items")
public class ItemsController {
#Autowired
private ItemsService itemsService;
and ItemsService:
public interface ItemsService {
Implementation class:
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
And some setting spring-mvc.xml:
<context:component-scan base-package="com.hdx.ssm.controller"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
How can i solve this problem?
You need to add #Service as shown below to your ItemsServiceImpl in order to Spring container to know that it is a Spring managed bean:
#Service
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
//other code
}

Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource

I am new to Spring. I am creating simple project in which I just call generateOutout() method using beans.
IOutputGenerator Interface:
package mian.java;
public interface IOutputGenerator {
public void generateOutput();
}
CsvOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class CsvOutputGenerator implements IOutputGenerator{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
JsonOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
OutputHelper.java:
package mian.java;
public class OutputHelper {
IOutputGenerator outputGeneratorCsv;
IOutputGenerator outputGeneratorJson;
public void generateOutput(){
outputGeneratorCsv.generateOutput();
outputGeneratorJson.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGeneratorCsv,IOutputGenerator outputGeneratorJson){
this.outputGeneratorCsv = outputGeneratorCsv;
this.outputGeneratorJson = outputGeneratorJson;
}
}
AppViaSpring.java (Main class):
package mian.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppViaSpring {
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Spring-Common.xml (Bean Class in main.resources package):
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="main.java.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="main.java.JsonOutputGenerator" />
</beans>
and Error is :
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource [Spring-Common.xml]; nested exception is java.lang.ClassNotFoundException: main.java.OutputHelper
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1141)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:758)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:422)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at mian.java.AppViaSpring.main(AppViaSpring.java:10)
Caused by: java.lang.ClassNotFoundException: main.java.OutputHelper
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
... 9 more
you forgot to add the JsonOutputGenerator bean for OutputHelper
try this:
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
<property name="outputGeneratorJson" ref="JsonOutputGenerator" />
</bean>
note you can also use context.getBean(OutputHelper.class), no casting will be required
edit:
on the further look at the problem. The setter you are using has two arguments which violates javaBean convention. There are few options.
1. You simply pass the map to the setter.
2. Create setter for each generator field.
3. You inject outputGeneratorCsv and outputGeneratorJson in the constructor - i would recommend that. In that case you would have to add constructor with two arguments (like your setter method) and modify the spring context xml to something like that:
<bean id="OutputHelper" class="main.java.OutputHelper">
<constructor-arg ref="outputGeneratorCsv"/>
<constructor-arg ref="outputGeneratorJson"/>
</bean>
here also some more info, why to use constructor injections:
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Setter injection versus constructor injection

Spring 3 Annotations with hibernate CRUD operations : #Autowired not working as expected

I'm currently using Spring 3 annotations along with hibernate 3 for the database connectivity. I also have to be using spring tiles.
My spring-servlet.xml is:
<context:annotation-config />
<context:component-scan base-package="com.xxx.controller,com.xxx.dao,com.xxx.service" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"
id="viewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/plugin/impl/tiles/springtiles-defs.xml</value>
</list>
</property>
</bean>
//Is this required????
<!-- <bean id="MyDAO" class="com.xxxx.MyDAOImpl"></bean>
<bean id="MyService" class="com.xxxx.MyServiceImpl"></bean> -->
My controller class :
#Controller
public class myController {
#Autowired
private MyService myService;
public myController() {
}
#RequestMapping(value="/index.do", method = RequestMethod.GET)
protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stubs
System.out.println(" Inside the controller ");
</beans>
And my serviceImpl class:
#Service("MyService")
public class MyServiceImpl implements MyService{
#Autowired
MyDAO myDAO;
And my DaoImpl class :
#Repository/*("myDAO")*/
public class MyDAOImpl implements MyDAO{
List<String> clientList;
#Autowired
private SessionFactory sessionFactory;
private Session session;
private Session currentSession() {
return this.sessionFactory.getCurrentSession();
}
#Override
public List<ClientInfoBean> getClientList(String currentQrt) throws DataStoreException {
// TODO Auto-generated method stub
return (List<ClientInfoBean>) this.currentSession().
createCriteria("Select * from myTable);
}
It still gives the below exceptions.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 97 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 99 more
So the problem is your packages:
You have definition of services and daos in: com.xxx.service and com.xxx.dao
and your implementation in: com.xxx.serviceImpl and com.xxx.daoImpl.
Add in also <context:component-scan base-package="com.xxx.serviceImpl,com.xxx.daoImpl"/>
Next problem you are facing is transactional management:
You havent defined it in spring configuration. This is an example how to do this:
<!-- Hibernate 3 Annotation SessionFactory Bean definition-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.jdbc.batch_size">${batchSize}</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
And after this you need to mark a method or your service implementation as #Transactional to make spring care of this.
The exception is clearly telling you that the bean is not configured
NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService]
Can you check the case of the bean names that you given in annotations are matching with the parameter name. myService vs MyService.
Also adding a setter might be a good idea as spring can call setter to inject the dependency instead of using Reflection to inject it.
When you define
#Service("MyService")
public class MyServiceImpl implements MyService{
}
or
#Repository("MyDAO")
public class MyDAOImpl implements MyDAO{
}
you are actually telling spring to create bean with the name "MyService" & "MyDAO"
when you define like
#Autowired
private MyService myService;
#Autowired
private MyDAO myDAO;
you are asking from spring to give bean(s) with the name "myService" & "myDAO".
Since spring creates bean with the name which is different from what are you asking, it is giving the error.
You have to keep name of the bean in the #Service & #Repository annotation same as the variable name for the Interface.
#Service("myService")
public class MyServiceImpl implements MyService{
}
private MyService myService;
As you qualified your service as "MyService" , you can add qualifier as below to find it. By default spring should autowire by type , so component scan should load your service. If you are defining beans partially in xml and expecting other services to be autowired, you have to add in your spring-servlet.xml
#Autowired
#Qualifier("MyService")
private MyService myService;
Also change your controller class as MyController instead of myController.
And remove the constructor myController(), spring will construct for you controller bean. Try to remove all your constructors in all your spring bean classes, spring will construct for you. For the beginning you can avoid qualifying the beans, remove the names in brackets( "MyService", "MyDao" etc....)
Use
#Service
public class MyServiceImpl implements MyService
Instead of
#Service("MyService")
public class MyServiceImpl implements MyService{

Spring Failed to Autowiring because of proxy-target-class="true" and <aop:aspectj-autoproxy />

I have the following spring configuration:
<context:annotation-config />
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="true" />
<tx:annotation-driven />
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.web,com.security" />
i have enabled proxy-target-class in global-method-security, because i want use #PreAuthorize annotation in the controller (i aware that spring team doesn't encourage this),
and using aop aspectJ as 'interceptor' in service when saving an object.
it seem that because the proxy configuration in global-method-security enabled and the default aop aspectj is using proxy implementation. it failed to autowiring the bean in all controller. proxying proxy ?
controller
#RequestMapping(value = "add")
#PreAuthorize("#securityPermission.validatePermission()")
public String add(Model model) {
//codes
}
my service class with #Aspect annotation
#SuppressWarnings("serial")
#Aspect
#Service
public class InterceptorServiceImpl extends BaseServiceImplementation implements InterceptorService {
#Autowired
private LogRepository logRepository;
#Around("execution(* com.repository.CardRequestRepository.save(..))")
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class,timeout = 30)
public Object checkProcess(ProceedingJoinPoint joinPoint) throws Throwable{
LOGGER.info("SERVICE : START Process checking Interceptor");
}
error logs :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalActivityController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.csl.cms.service.ApprovalActivityService com.csl.cms.web.ApprovalActivityController.approvalActivityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalActivityServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.csl.cms.repository.CardRequestRepository com.csl.cms.service.serviceimplementasi.ApprovalActivityServiceImpl.cardRequestRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cardRequestRepository': Post-processing of the FactoryBean's object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy572]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:376)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy572]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:213)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1598)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:162)
... 65 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:201)
... 72 more
repository class
public interface CardRequestRepository extends JpaRepository<CardRequest, Long>, CardRequestRepositoryCustom {
public List<CardRequest> findByCardholderId(Long cardholderId);
#Query("Select cr FROM CardRequest cr "
+ "LEFT JOIN FETCH cr.cardholder ch "
+ "LEFT JOIN FETCH ch.identityDocument "
+ "LEFT JOIN FETCH cr.program p "
+ "WHERE cr.id = :id")
public CardRequest findOneFetching(#Param("id") Long cardholderId);
}
public interface CardRequestRepositoryCustom {
public List<CardRequest> findCardRequestWithDatatablesCriterias(DatatablesCriterias criterias);
.....
service impl class
#SuppressWarnings("serial")
#Service
public class ApprovalActivityServiceImpl extends BaseServiceImplementasi implements ApprovalActivityService {
#Autowired
private ApprovalActivityRepository approvalActivityRepository;
...
#Autowired
private MessageSource messageSource;
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public ApprovalActivity findOne(Long id) {
LOGGER.info("SERVICE : ApprovalActivity findOne id =" + id);
return approvalActivityRepository.findOne(id);
}
}
baseserviceimpl class
public abstract class BaseServiceImplementasi
implements Serializable
{
protected transient Logger LOGGER = Logger.getLogger(getClass());
}
is it possible using aop:aspectj-autoproxy and enable proxy-target-class at same time ? or anyone have another suggestion ? :)
Failed Autowire Issue resolved
as suggestion from #M.Deinum i resolved my autowiring issue, added proxy-target-class="true" attribute in :
<tx:annotation-driven />
<cache:annotation-driven />
<aop:aspectj-autoproxy />
and i remove #Service in the class with #Aspect annotation.
note : in the InterceptorServiceImpl i was using #Service because i want #Autowiring to call repository/service bean
aspect class issue that occurred :
it seem because i have removed the #Service annotation in my aspect class, the aop aspectj somehow did not executed, and no error in my logs.
I resolved my issue, it seem because the using of data jpa (JpaRepository) in my repository class.
here is my xml configuration :
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="true"/> //enabled proxy to use #preAuthorize in controller
<tx:annotation-driven />
<cache:annotation-driven />
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.xxx.xxx.service.serviceimplementasi" />
<jpa:repositories base-package="com.csl.cms.repository" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />
data jpa configs :
<!--Spring Data JPA Configuration-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="c3p0DataSource-1" />
<property name="packagesToScan" value="com.xxx.xxx.entity"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${database.dialect}" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
repository class :
public interface CardRequestRepository extends JpaRepository<CardRequest, Long>, CardRequestRepositoryCustom {
public List<CardRequest> findByCardholderId(Long cardholderId);
in CardRequestRepositoryCustom class, create a custom save method using entityManager, so it will not depends on JpaRepository class.
public class CardRequestRepositoryImpl implements CardRequestRepositoryCustom {
#PersistenceContext
private EntityManager em;
#Override
public CardRequest customSave(CardRequest cardRequest) {
em.persist(cardRequest);
return cardRequest;
}
i also changed my point cut class in my aspect class, use the repository custom class :
#SuppressWarnings("serial")
#Aspect
#Component
public class ApprovalInterceptorServiceImpl extends BaseServiceImplementasi implements ApprovalInterceptorService {
#Autowired
private LifecycleLogRepository lifecycleLogRepository;
#Autowired
private ApprovalDefinitionRepository approvalDefinitionRepository;
#Around("execution(* com.xxx.xxx.repository.repositoryimplementasi.CardRequestRepositoryImpl.customSave(..))")
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class,timeout = 30)
public CardRequest checkApprovalProcess(ProceedingJoinPoint joinPoint) throws Throwable{
LOGGER.info("SERVICE : START Approval Process checking Interceptor");
System.out.println("SERVICE : START Approval Process checking Interceptor");
Object messageParam[] = new Object[1];
Object[] objs = joinPoint.getArgs();
CardRequest cardRequest = (CardRequest) objs[0];
....
in the aop aspect class, using #Component to autowiring the service bean and do not extends the repository class using jpaRepository, instead use/create a custom repository class and entityManager to save an object. with this configuration and codes my proxy class problem fixed.
if i applied #Component, #Autowired and using jpaRepository in my aspect class, the repository bean class failed to autowiring. still does not know why it happen.

Inject primitive properties to Spring bean when using #Autowired?

try to inject myInt of the following through Spring
public class MyBean {
#Resource (name="myValue")
private int myInt;
Any idea? I have got the following post. But it don't work for me. I still get the following error message.
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'myValue' must be of type [int], but was actually of type [java.lang.Integer]
Detail:
The following is the test servlet that I have create for this testing.
#WebServlet("/myTestServlet")
public class myTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public myTestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request);
}
private void doProcess(HttpServletRequest request)
{
WebApplicationContext applicationContext =
WebApplicationContextUtils.getWebApplicationContext(
((HttpServletRequest) request).getSession().getServletContext());
MyService service = applicationContext.getBean(MyService.class);
service.doPrint();
}
}
The following is service bean that I am using for this test.
public class MyService {
// #Autowired
// #Qualifier("myValue")
#Resource (name="myValue")
private int myInt;
public void doPrint ()
{
System.out.println("myInt is " + myInt);
}
}
The following is the applicationContext.xml that I am using
<context:annotation-config />
<bean id="myService" class="tsttst.MyService" >
</bean>
<!-- Global configuration -->
<bean id="myValue" class="java.lang.Integer" factory-method="valueOf">
<constructor-arg value="1000" />
</bean>
The following is the error that I have got when use #Resource
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'myValue' must be of type [int], but was actually of type [java.lang.Integer]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:349)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
... 21 more
However, if I use #Autowired, the following error will be resulted
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int tsttst.MyService.myInt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [int] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=myValue)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283)
... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [int] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=myValue)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:914)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:783)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:697)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 23 more
How is the int defined?
If it is property (with a placeholder configurer for example) you can use #Value.
If it is defined with <bean id="myValue" class="java.lang.Integer">..</bean> with either constructor-arg or a factory-method, then #Autowired / #Resource should work.
As for autounboxing - it seems it does not work, so you'd need an Integer.
You can also try <util:constant .. />

Resources