I have a Account Business Service which in which i am coding my Business Requirements. And for that Business Service i have a Advice class of SecurityCheck
package com.jlcindia.spring.bservices;
public class AccountService {
public void getBal() {
System.out.println("Get bal is successfull");
}
public void myDeposit() {
System.out.println("MY Deposit is successfull");
}
public void myWithdraw() throws Exception {
System.out.println("WIthdraw begin");
int i=0;
if (i == 1){
throw new InSufficientFundsException();
}
System.out.println("WIthdraw end");
}
}
The advice class is as follows:
package com.jlcindia.spring.mservices;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class SecurityService {
#Pointcut(value="execution(* com.jlcindia.spring.bservices.AccountService.my*(..))")
public void pc1(){}
#Pointcut(value="execution(* com.jlcindia.spring.bservices.CustomerService.del*(..))")
public void pc2(){}
#Around("pc1() or pc2()")
public void verifyUser(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("SS-verifyUser()-Begin");
pjp.proceed();
System.out.println("SS-verifyUser()-END");
}
}
I use annotation-config.xml file to configure the Business Service and Advice class as follows:
<bean id="as" class="com.jlcindia.spring.bservices.AccountService" />
<bean id="security" class="com.jlcindia.spring.mservices.SecurityService"/>
Here is the code to test it:
package com.jlcindia.spring.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jlcindia.spring.bservices.AccountService;
public class Client {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
AccountService ast = (AccountService)ctx.getBean("as");
ast.myDeposit();
ast.getBal();
try{
ast.myWithdraw();
}catch(Exception e){
System.out.println("***sorry****");
}
}
}
When I am running my client code to test the services whether the advice is applying or not I am getting this exception;
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'as' defined in class path resource [application-context.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut pc1
The full stack trace is:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'as' defined in class path resource [application-context.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut pc1
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.jlcindia.spring.aop.Client.main(Client.java:11)
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut pc1
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:316)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:195)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:181)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:162)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:200)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:254)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:286)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:117)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359)
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.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 11 more</h3>
Please help to figure out why this error occuring while creating the bean 'as'(AccountService). I don't have much knowledge on AOP, i am learner now... so please i need a little help on this question. thank you for your patience to read this...
There is a syntax error in your pointcut. Please change
#Around("pc1() or pc2()")
to
#Around("pc1() || pc2()")
P.S.: And please use less chaotic source code and prose text formatting next time, it took me 5+ minutes to edit your question in order to make it more readable for myself and others.
Related
I am writing a springboot project, where I am picking a .properties file from application.properties
application.properties
sample.prop.file=com.example.handler/signature.properties
and have created a Component to pass this file as InputStream and initialise the Bean
Handler.java
#Component
public class Handler extends DefaultHandler {
private Resource properties;
public Handler(#Value("${sample.prop.file}") Resource properties) throws IOException {
this.properties = properties;
this.props = new Properties();
this.props.load(this.properties.getInputStream());
}
}
In my service I create an instance of Handler.java and add it as BindingProvider
Service.java
#Service
public class Service {
#Autowired
private Handler handler;
public void doSomething() {
//some logic
someMethod(handler);
}
After following some similar queries I am trying constructor injection and using #Autowired in my Service to make sure my #Component is initialised before it is called.
But still upon running the project I am getting an error below.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Handler' defined in file [/Users/abc/APP/testService/target/classes/com/example/handler/Handler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.handler.Handler]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
... 32 common frames omitted
Any inputs/comments are appriciated.
Thanks!
If the file in classpath. put classpath: as follows.
#Value("classpath:${sample.prop.file}")
You should know that Resource is annotation and you can't create an instance of it.
So you may change properties from Resource to String because #Value("${sample.prop.file}") returns String. Your class may become like so:
#Component
public class Handler extends DefaultHandler {
private Properties props;
public Handler(#Value("${sample.prop.file}") String properties) throws IOException
{
this.props = new Properties();
String p = Paths.get(properties).toAbsolutePath().toString();
InputStream in = new FileInputStream(p);
this.props.load(in);
}
}
But make sure that the new file is accessable, i.e. in some absolute path!
I was trying to understand difference between #component and #Bean in Spring framework, and referred to this SO question.
Based on the answer, I got a fair understanding, and tried to reinforce the concept by implementing a simple example (to check whether I really understood the concept).
The below is the code which I wrote. I wanted to see #Bean for "third party" libs (so that it can be instantiated using #Bean annotation)
package com.example.thirdparty.code;
public class ThirdPartyUtil {
public ThirdPartyUtil() {
}
public void print(String str) {
System.out.println("String passed is --> " + str);
}
}
In above, I tried to simulate a "third party lib/class - NON spring" which isn't a spring based (and so there won't be any #component in that class.
Now, below is the main application which I created:
package com.example.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import com.example.thirdparty.code.ThirdPartyUtil;
#Configuration
#ComponentScan(basePackages = { "com.example.spring" })
#Component
public class SpringBasedMainApp {
#Autowired
private ApplicationContext ctx;
#Autowired
private static ThirdPartyUtil thirdPartyUtil;
#Bean
public ThirdPartyUtil beanThirdPartyUtil() {
try {
Class c = getClass().getClassLoader().loadClass("com.example.thirdparty.code.ThirdPartyUtil");
return (ThirdPartyUtil) ctx.getBean(c);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Exception");
}
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringBasedMainApp.class);
System.out.println("thirdPartyUtil is " + thirdPartyUtil);
}
}
I was hoping that using #Bean annotation, it would create ThirdPartyUtil as Spring bean, and then inject using #Autowired into field thirdPartyUtil.
However, when I run this program, I got altogether a surprising exception, listed below:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanThirdPartyUtil' defined in com.example.spring.SpringBasedMainApp: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.thirdparty.code.ThirdPartyUtil]: Factory method 'beanThirdPartyUtil' threw exception; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanThirdPartyUtil': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:88)
at com.example.spring.SpringBasedMainApp.main(SpringBasedMainApp.java:41)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.thirdparty.code.ThirdPartyUtil]: Factory method 'beanThirdPartyUtil' threw exception; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanThirdPartyUtil': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
... 14 more
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanThirdPartyUtil': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:339)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:215)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:224)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1112)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:407)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:341)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101)
at com.example.spring.SpringBasedMainApp.beanThirdPartyUtil(SpringBasedMainApp.java:33)
at com.example.spring.SpringBasedMainApp$$EnhancerBySpringCGLIB$$d93c67f4.CGLIB$beanThirdPartyUtil$0(<generated>)
at com.example.spring.SpringBasedMainApp$$EnhancerBySpringCGLIB$$d93c67f4$$FastClassBySpringCGLIB$$9349d69b.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.example.spring.SpringBasedMainApp$$EnhancerBySpringCGLIB$$d93c67f4.beanThirdPartyUtil(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 15 more
I didn't understand why it is giving this exception. I am creating an applicationContext using AnnotationConfigApplicationContext and passing the necessary details to it.
I expected it to work, however got the above exception (which I have seen maiden time).
Why has this exception been thrown, is my understanding not correct about #Bean?
The goal of the #Bean annotation is to annotate a method whose responsibility is to create an object, that will then be registered as a bean by Spring.
But inside your method, you ask Spring (using ctx.getBean()) to give you the bean that you're currently creating. So you get that exception.
Here's what your methd should look like:
#Bean
public ThirdPartyUtil beanThirdPartyUtil() {
return new ThirdPartyUtil();
}
To extend #JB Nizet answer, instantiate your third party class in spring constructor like below.
#Autowired
private static ThirdPartyUtil thirdPartyUtil;
#Autowired
public SpringBean() {
this.thirdPartyUtil = new ThirdPartyUtil();
}
im trying to create some pointcuts and before advices for Repositories in order to enable filtering over entitymanager for some Repositories in Spring Data in Spring Boot. i also have web and service layer in project and AspectLogging works for both. But i couldnt do same for repositories. i have been struggling for 2 days and i tried so many things for fix it. i read almost every docs, issues and threads about this( proxy issues CGlib and JDK Proxy etc). i used jhipster for creating project.
i cant deploy Application except #Pointcut with CrudRepository. and even its deployed #Before isnt called for a method call in Repository. i think i have a similar Problem like in following question. proxy confusion
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.zzz.business.repository.ApplyRepository com.xxx.zzz.web.rest.applyResource.ApplyRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applyRepository': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: 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.$Proxy173
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 61 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applyRepository': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: 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.$Proxy173
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:116)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1523)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:314)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 63 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy173]: 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.$Proxy173
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:212)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:447)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:333)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1719)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:113)
... 70 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy173
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:56)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 77 more
Does anyone know what its could be ?
Classes and Configs look like following.
Repository:
public interface ApplyRepository extends JpaRepository<Apply,Long>,QueryDslPredicateExecutor<Apply> {
public Page<Apply> findAll(Predicate predicate, Pageable p);
}
...
}
Database Config:
#Configuration
#EnableJpaRepositories("com.xxx.zzz.business.repository")
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableTransactionManagement//(proxyTargetClass = false)
public class DatabaseConfiguration {
....
AspectJ Config:
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = true)
// #EnableLoadTimeWeaving(aspectjWeaving = ... )
public class LoggingAspectConfiguration {
...
System Architecture:
#Aspect
public class SystemArchitecture {
/**
* A join point is in the web layer if the method is defined
* in a type in the com.xyz.someapp.web package or any sub-package
* under that.W
*/
#Pointcut("within(com.xxx.zzz.web.rest..*)")
public void inWebLayer() {
}
/**
* A join point is in the service layer if the method is defined
* in a type in the com.xyz.someapp.service package or any sub-package
* under that.
*/
#Pointcut("within(com.xxx.zzz.business.service..*)")
public void inServiceLayer() {
}
/**
* A join point is in the data access layer if the method is defined
* in a type in the com.xyz.someapp.dao package or any sub-package
* under that.
*/
#Pointcut("within(com.xxx.zzz.business.repository..*)")
public void inDataAccessLayer() {
}
/**
* All layers
*/
#Pointcut("inWebLayer() || inServiceLayer() || inDataAccessLayer()")
public void inALL(){
}
#Pointcut("within(org.springframework.data.repository.CrudRepository)")
//#Pointcut("execution(*org.springframework.data.repository.Repository+.* (..))")
//#Pointcut("execution(* com.xxx.zzz.business.repository+.*(..))")
//#Pointcut("execution(* org.springframework.data.jpa.repository.JpaRepository+.*(..))")
//#Pointcut("execution(* com.xxx.zzz.business.repository.ApplyRepository.*(..))")
public void inDATAExec(){}
}
FilterAspect:
#Aspect
#Transactional
public class FilterAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#PersistenceContext
private EntityManager entitymanager;
#Before("com.xxx.zzz.aop.logging.SystemArchitecture.inDATAExec())") // "execution(* com.xxx.zzz.business.repository.InvoiceRepository.*(..))"
public void doAccessCheck() {
if (TransactionSynchronizationManager.isActualTransactionActive() && SecurityUtils.isAuthenticated()) {
Session session = entitymanager.unwrap(Session.class);
session.enableFilter("GLOBAL_FILTER").setParameter("customerId", SecurityUtils.getCurrentCustomerId());
}
}
EDIT: i solved problem. it was related somehow to wrong pointscuts and names. i tried to change pointcuts for custom annotation in Repository. it doesnt work for method or class level. i read in following links issues about this.
advice 1
advice 2
im struggling for hours for target and annotation. but no result.
is it really imposible to add custom annotations in Spring Data Repositories for advicing ?
Annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
//#Inherited
public #interface CustomerRequired {
String value() default "customerrequired";
}
Repository:
public interface InvoiceRepository extends JpaRepository<Invoice,String>, QueryDslPredicateExecutor<Invoice> {
#CustomerRequired
public Page<Invoice> findAll(Predicate predicate, Pageable p);
...
}
Pointcut and Advice:
#Pointcut(value = "#target(customerRequired)",argNames = "customerRequired")
public void targetCustomer(#SuppressWarnings("unused") CustomerRequired customerRequired) {/**/}
#Before(value = "com.xxx.zzz.aop.logging.SystemArchitecture.targetCustomer(customerRequired) && com.xxx.zzz.aop.logging.SystemArchitecture.inDataLayer()")
public void doAccessCheck(JoinPoint joinPoint, CustomerRequired customerRequired) {
if (TransactionSynchronizationManager.isActualTransactionActive() && SecurityUtils.isAuthenticated()) {
Session session = entitymanager.unwrap(Session.class);
session.enableFilter("GLOBAL_FILTER").setParameter("customerId", SecurityUtils.getCurrentCustomerId());
}
}
Instead of using
#Pointcut("within(org.springframework.data.repository.CrudRepository)")
public void inDATAExec(){}
use like following
#Pointcut("this(org.springframework.data.repository.Repository)")
public void inDATAExec(){}
and what it does is
any join point (method execution only in Spring AOP) where the
proxy implements the Repository interface
You can have a look it at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
Hope it helps!
Im trying to start Tomcat but when I try start it im getting the following error
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countriesDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.fexco.helloworld.web.util.CustomHibernateDaoSupport.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
CountriesDao
package com.fexco.helloworld.web.dao;
import com.fexco.helloworld.web.model.Countries;
public interface CountriesDao {
void save(Countries countries);
void update(Countries countries);
void delete(Countries countries);
Countries findByCountry(String country);
}
The start of CountriesDaoImpl
package com.fexco.helloworld.web.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.fexco.helloworld.web.model.Countries;
import com.fexco.helloworld.web.util.CustomHibernateDaoSupport;
#Repository("countriesDao")
public class CountriesDaoImpl extends CustomHibernateDaoSupport implements CountriesDao{
public void save(Countries countries){
getHibernateTemplate().save(countries);
}
......
}
Some of Application-config.xml
<bean id="countriesDao" class="com.fexco.helloworld.web.dao.CountriesDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
....
<context:annotation-config />
<context:component-scan base-package="com.fexco.helloworld.web" />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
CustomHibernateDaoSupport class
package com.fexco.helloworld.web.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{
#Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
}
Is the error because CountriesDaoImpl isnt really implementing CountriesDao?
Does anyone know how to solve this error?
Thanks
It seems you do not have session factory defined in your dao Implementation class. You should defined one if not already defined And avoid using both configurations It will messed up things i.e
#Autowired
#Qualifier("sessionFactory")
public void seSessionFactory(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
I´m pretty new to Spring, and I´m currently struggling with an exception being thrown when I´m attempting to extend JdbcUserDetailsManager since I need additional features besides the ones provided. The class signature looks looks like this, with a default constructor.
#Repository
public class PrimeUserDetailsManager extends JdbcUserDetailsManager implements CustomUserDetailsManager {
public static String CUSTOM_USERS_BY_USERNAME_QUERY = "select username,password,enabled from users where username like ?%";
public static String FIND_ALL_USERS_QUERY = "select username,password,enabled from users";
#Override
public List<UserDetails> loadUsersByUsername(String username) {
return super.loadUsersByUsername(username);
}
#Override
public List<UserDetails> findAllUsers() {
return getJdbcTemplate().query(FIND_ALL_USERS_QUERY, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
return new User(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
}
});
}
}
}
My custom Interfaces looks like this:
public interface CustomUserDetailsManager extends UserDetailsManager {
public List<UserDetails> loadUsersByUsername(String username);
public List<UserDetails> findAllUsers();
}
Simple autowire:
#Service("userService")
public class UserServiceImpl implements UserService{
#Autowired
public UserServiceImpl(CustomUserDetailsManager customUserDetailsManager) {
this.customUserDetailsManager = customUserDetailsManager;
}
private CustomUserDetailsManager customUserDetailsManager;
....
}
And in my ApplicationContext, I have this:
<beans:bean id="jdbcUserService" class="org.primefaces.examples.moviecollector.custom.PrimeUserDetailsManager">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="enableGroups" value="true"/>
<beans:property name="enableAuthorities" value="false"/>
</beans:bean>
Still, when staring my application, I get the exception below, so apperently I must have missed something? Can someone please tell me what?
Complete stacktrack:
2011-sep-07 13:08:49 org.apache.catalina.core.StandardContext listenerStart
ALLVARLIG: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userBean' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\beans\UserBean.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.security.provisioning.GroupManager]: : Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:730)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
... 23 more
Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.jdbc.core.support.JdbcDaoSupport.checkDaoConfig(JdbcDaoSupport.java:112)
at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 34 more
EDIT:
I´ve included the entire body of PrimeUserDetailsManager above. Here´s the dataSource definition:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
You've got two beans. One is defined in XML. There's another one being created because you've annotated your class with #Repository. That's the one giving you the trouble because you haven't given it any instructions about wiring the required "'dataSource' or 'jdbcTemplate'". Note in the exception that the bean's name is given as "primeUserDetailsManager". That's the lower-cased simple class name, which is the default name for beans created via component scanning with annotations.
I create an intermediate JdbcDaoSupport derived super class that all my DAO classes extend from that looks like this:
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class MyJdbcDaoSupport extends JdbcDaoSupport {
#Autowired private DataSource dataSource;
#PostConstruct
private void initialize() {
setDataSource(dataSource);
}
}
This assumes you have a data source bean with id "dataSource", as shown by the OP.
Works for me in Spring 4.x but should work with earlier versions too.
The only way I managed to solve is by defining following in my DAO.
private SimpleJdbcTemplate simpleJdbcTemplate;
protected SimpleJdbcTemplate getSimpleJdbcTemplate() {
return simpleJdbcTemplate;
}
#Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
It seems the SimpleJdbcDaoSupport does not have #Autowired annotation to its setDataSource method.
This works even in spring 2.5
/**
* Sets the parent class DataSource to the auto-wired data source.
*
*
*/
#Autowired
public void setParentDataSource(
#Qualifier("dataSource") DataSource dataSource) {
super.setDataSource(dataSource);
}