REST API: org.springframework.beans.factory.UnsatisfiedDependencyException: - java

I am building a REST API and can't seem to get rid of the org.springframework.beans.factory.UnsatisfiedDependencyException, I can't spot the issue in this. I will appreciate a fresh insight into this.
p.s: Using mongo DB for this
first off the full error
2020-05-04 01:16:31.468 WARN 14412
--- [ main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization -
cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productController':
Unsatisfied dependency expressed through field 'productService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productServiceImpl':
Unsatisfied dependency expressed through field 'productRepo';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productRepo':
Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException:
No property id found for type Product!
public class Product {
#Id
private int ProductId;
// and other variables plus setters and getters
#Repository
public interface ProductRepo extends MongoRepository<Product, String> {
// methods
}
public interface ProductService {
// methods
}
#Service
public class ProductServiceImpl implements ProductService {
#Autowired
private ProductRepo productRepo;
// implementations
}

Try changing the Product class as the following:
#Entity
public class Product {
#Id
private String productId; // MongoRepository<Product, String>
// methods
}
In the Product class the #Entity annotation is missing and the productId should be a String, as specified in the repository.
Or change to extends MongoRepository<Product, Integer> if you want to keep the current field type.
In any case, they should match.

Make You That Your Spring Application Knows Where Your Classes Resides.
Use #ComponentScan(basePackages = "com.package").
Moreover If Your Product Class Is Something That You Want to Persist Mark It With #Entity So Spring Knows about It And Creates A Bean Out Of it.
Mark Your interface ProductService with #service, So that Spring Knows About it.

Related

Can we Autowired below class into Configuration class in springboot

I have a Component class and a config class,so can we autowire component class which uses #value internally,I tried using it but it throws exception,Can anyone please help me understanding
#Component
public class UserAction {
#Value("${cp.user.name}")
private String userName;
#Value("${cp.user.actiontype}")
private String actionType;
#Value("${cp.user.designation}")
protected Designation designation;
public void show() {
System.out.println(userName);
System.out.println(actionType);
System.out.println(designation);
}
}
#Configuration
#ComponentScan("com.example")
public class AppConfig {
#Autowired
UserAction userAction;
------
}
So My question is : can I autowire my UserAction bean into my AppConfig class?
I tried using it but its throwing exception,so can we autowire a component which internally uses #value :
Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'AppConfig ': Unsatisfied dependency expressed through field 'userAction'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userAction': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'cp.user.actiontype' in value "${cp.user.actiontype}"
Yes you can Autowire beans in Configuration class, but the issue here is that a property in your bean has no value set in properties/yml file
#Value("${cp.user.actiontype}")
set the property cp.user.actiontype in your .properties or .yml file

How the directory structure for SpringBoot MongoDB CrudRepositoryCustom Implementation should be organized?

I have created a simple maven project using SpringBoot and MongoDB. I have two repository implementations i.e. StudentRepository and StudentRepositoryCustom. StudentRepository extends in built MongoRepository and the custom repository. The custom repository methods are implemented in StudentRepositoryImpl. The applications runs without errors when I put StudentRepository, StudentRepositoryCustom and StudentRepositoryImpl in same package i.e. com.aman.springboot.repository. But the application throws error when the implementation class is moved to some other package let's say com.aman.springboot.impl.
What am I doing wrong ?
Here's the main class:
package com.aman.springboot.client;
#SpringBootApplication(scanBasePackages = "com.aman.springboot")
public class ApplicationLauncher {
public static void main(String[] args) {
SpringApplication.run(StudentController.class, args);
}
}
Here's RestController class:
package com.aman.springboot.controller;
#RestController
#EnableAutoConfiguration
#EnableMongoRepositories(basePackages = "com.aman.springboot.repository")
#RequestMapping(value = "/student")
public class StudentController {
#Autowired
private StudentRepository studentRepository;
#RequestMapping(value = "/getStudent", method = RequestMethod.GET)
public StudentRepo getStudent(#RequestParam(required = true) int id) {
return studentRepository.findStudentById(id);
}
#RequestMapping(value = "/removeStudent", method = RequestMethod.POST)
public void removeStudent(#RequestBody(required = true) StudentRepo
studentRepo) {
studentRepository.deleteStudent(studentRepo);
}
}
Here's StudentRepository:
package com.aman.springboot.repository;
#Repository
public interface StudentRepository extends MongoRepository<StudentRepo,
String>, StudentRepositoryCustom {
public StudentRepo findStudentById(int id);
}
Here's StudentRepositoryCustom:
package com.aman.springboot.repository;
public interface StudentRepositoryCustom {
public void deleteStudent(StudentRepo studentRepo);
}
Here's StudentRepositoryImpl:
package com.aman.springboot.impl;
#Service
public class StudentRepositoryImpl implements StudentRepositoryCustom{
#Autowired
private MongoTemplate mongoTemplate;
#Autowired
private StudentRepo student;
#Override
public void deleteStudent(StudentRepo studentRepo) {
mongoTemplate.remove(studentRepo);
}
}
As you can see both interfaces or repositories are in same package but the implementation class for StudentRepositoryCustom interface is in different package. In this case the application throws error while deploying:
Here's the stack trace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'studentController': Unsatisfied dependency
expressed through field 'studentRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'studentRepository': Invocation of init method failed; nested
exception is org.springframework.data.mapping.PropertyReferenceException: No
property deleteStudent found for type StudentRepo! at
org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject
(AutowiredAnnotationBeanPostProcessor.java:586)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.beans.factory.annotation.InjectionMetadata.inject
(InjectionMetadata.java:91) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at
org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues
(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-
5.0.8.RELEASE.jar:5.0.8.RELEASE] at
.
.
.
.
org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE] at
com.aman.springboot.client.ApplicationLauncher.main
(ApplicationLauncher.java:17) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'studentRepository': Invocation of init method
failed; nested exception is
org.springframework.data.mapping.PropertyReferenceException: No property
deleteStudent found for type StudentRepo! at
org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.initializeBean
(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-
5.0.8.RELEASE.jar:5.0.8.RELEASE] at
.
.
.
.
tializeBean(AbstractAutowireCapableBeanFactory.java:1695) ~[spring-beans-
5.0.8.RELEASE.jar:5.0.8.RELEASE] ... 29 common frames omitted
The application works fine if I move the StudentRepositoryImpl class to package in which the repositories are i.e. com.aman.springboot.repository.
Any help would be appreciated !!! Thanks.
I solved my problem by refactoring the package structure for custom repository and its implementation class. What I understand from the problem is Spring looks for implemented classes for repositories in child packages.
For example, if repository is defined in com.foo.repo, it's implementing class should be in com.foo.repo.impl.
The repositories should be defined in top level packages and the implementing class should be in same package or it's child package.

Spring Bean is not autowired

I have a problem with Spring bean DefaultConfigurationService initialization that is extended from abstract class. I am totally stuck.
Class hiearchy is as follows:
public interface ConfigurationService {
TaxPayer getTaxPayer();
}
This class is mentioned to be useful for services that need to be initialized:
public abstract class BaseInitializationAwareService {
private boolean initialized = false;
public abstract void initialize();
protected void checkInitialization() {
if (!initialized) {
initialize();
}
}
protected void setInitialized() {
this.initialized = true;
}
}
This class acts as base class for Configuration service.
public abstract class BaseConfigurationService extends BaseInitializationAwareService implements ConfigurationService {
}
And with this bean, that acts as a configuration service, is a problem:
public class DefaultConfigurationService extends BaseConfigurationService {
private TaxPayerService taxPayerService;
#Autowired
public void setTaxPayerService(TaxPayerService taxPayerService) {
Assert.notNull(taxPayerService);
this.taxPayerService = taxPayerService;
}
public void initialize() {
Optional<TaxPayer> dbtaxPayer = taxPayerService.getActiveTaxPayer();
if (!dbtaxPayer.isPresent()) {
throw new IllegalStateException("Tax payer setting not found!");
}
this.taxPayer = dbtaxPayer.get();
setInitialized();
}
// the rest omitted...
}
when I'm creating DefaultConfigurationService bean:
#Bean
public BaseConfigurationService configurationService() {
DefaultConfigurationService configurationService = new DefaultConfigurationService();
configurationService.initialize();
return configurationService;
}
then taxPayerService in DefaultConfigurationService is null - it seems that is not autowired.
Can it be connected to the fact that DefaultConfigurationService is extended from abstract class?
TaxPayer service bean:
#Bean
public TaxPayerService taxPayerService() {
DatabaseTaxPayerService taxPayer = new DatabaseTaxPayerService();
return taxPayer;
}
This bean is probably never initialized...
Thats is a exception:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webSecurityConfig.ApiSecurity':
Unsatisfied dependency expressed through method
'setContentNegotationStrategy' parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration':
Unsatisfied dependency expressed through method 'setConfigurers'
parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'passwordRecoverController': Unsatisfied
dependency expressed through method 'setUserService' parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'defaultUserService': Unsatisfied
dependency expressed through method 'setNotificationService' parameter
0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'notificationService': Unsatisfied
dependency expressed through method 'setConfigurationService'
parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'configurationService' defined in class path
resource [com.example.config/AppConfig.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.example.services.BaseConfigurationService]: Factory
method 'configurationService' threw exception; nested exception is
java.lang.NullPointerException
For example, bean that needs BaseConfigurationService:
public class EmailNotificationService extends BaseService implements NotificationService {
private BaseConfigurationService configurationService;
#Autowired
public void setConfigurationService(BaseConfigurationService configurationService) {
Assert.notNull(configurationService);
this.configurationService = configurationService;
}
// the rest omitted...
}
#update 1
Bean initialization example with internal dependencies to another beans:
#Bean
public TransactionDataService transactionDataService() {
return new DefaultTransactionDataService();
}
and DefaultTransactionDataService:
public class DefaultTransactionDataService implements TransactionDataService {
private PrivateKeyService privateKeyService;
#Autowired
public void setPrivateKeyService(PrivateKeyService privateKeyService) {
Assert.notNull(privateKeyService);
this.privateKeyService = privateKeyService;
}
}
and bean dependency
#Bean
public PrivateKeyService privateKeyService() {
return new DefaultPrivateKeyAwareService();
}
and it works.
It is related to your instruction to Spring how to initialize your bean:
#Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
So when you create instance of your class manually your have to set all class field manually as well.
It can be done like this:
#Bean
public BaseConfigurationService configurationService() {
DefaultConfigurationService configurationService = new DefaultConfigurationService();
configurationService.setTaxPayerService(taxPayerService());
configurationService.initialize();
return configurationService;
}
Or move dependency directly to constructor, so dependency of your DefaultConfigurationService will be more obvious:
#Bean
public BaseConfigurationService configurationService() {
DefaultConfigurationService configurationService = new DefaultConfigurationService(taxPayerService());
configurationService.initialize();
return configurationService;
}
Good description

Error creating bean because it's an interface?

Basically I have two beans implementing the same interface. One is for profile "default" and another "integration".
public interface SomeClientIfc { ... }
#Component
#Profile(value={"functional", "integration"})
public class StubSomeNIOClient implements SomeClientIfc {...}
public class SomeNIOClient implements SomeClientIfc {...}
#Configuration
#Profile("default")
public class SomeClientConfiguration {
#Bean
public SomeClientIfc someClient() {
...
SomeNIOClient someClient = new SomeNIOClient(numberOfParititions, controllerHosts, maxBufferReadSize,
connectionPoolSize);
return someClient;
}
}
In prod code it's
#Autowired
public SomeUserResolver(..., SomeClientIfc someClient) {...}
So far so good and I did see the stub bean is called in an integration test. Then I want to inject some test data into the stub bean in my integration test:
#ContextConfiguration(locations = {"/configProperties.xml", "/integrationTests.xml", ...})
#ActiveProfiles("integration")
public class SomeTestBase {
#Autowired
private SomeClientIfc someClientIfc;
}
However, when running the test I got error message
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someClientIfc': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.audiencescience.some.client.SomeClientIfc]: Specified class is an interface
I even tried to replace SomeClientIfc with StubSomeNIOClient but still get the same message, even though StubSomeNIOClient is not an interface.
You should add a Qualifier annotation along with the Autowired one to specify which bean must be instantiated:
#Autowired
#Qualifier("my-bean")
The reason it's trying to inject the SomeClientIfc is because you called the variable 'someClientIfc'.
In the integration environment you have all 3 classes initialized: SomeClientIfc, StubSomeNIOClient, and SomeNIOClient. This creates a confusion for spring, luckily there are ways to resolve that confusion.
One way is as mentioned above by Little Santi, another way is to name your variable 'stubSomeNIOClient' see code below
#ContextConfiguration(locations = {"/configProperties.xml", "/integrationTests.xml", ...})
#ActiveProfiles("integration")
public class SomeTestBase {
#Autowired
private SomeClientIfc stubSomeNIOClient;
}

Aspect Advice for Spring Data Repository doesnt work

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!

Categories