public abstract class AService<T> {
public T needsToBeAdvised(T param) {
T result = doSomething(param);
return result;
}
}
#Service
public class BService extends AService<B> {
#Override
public T needsToBeAdvised(T param) {
return super.needsToBeAdvised(param);
}
}
#Service
public class CService extends AService<C> {}
// (B & C implement an interface AType)
#Component
#Aspect
public class MyAspect {
#Pointcut("execution(* package.AService+.needsToBeAdvised(*))")
private void aNeedToBeAdvised() {}
#AfterReturning(pointcut="aNeedToBeAdvised()", returning="param")
public void interceptNeedsToBeAdvised(JoinPoint joinPoint, AType param) {
// some action
}
}
Given this setup:
bService.needsToBeAdvised(bParam) //is intercepted
but,
cService.needsToBeAdvised(cParam) //is NOT.
How do I achieve this without overriding needsToBeAdvised() in CService?
EDIT:
I should add that BService and CService are both in the same package.
If I change my point-cut to the following:
#Pointcut("execution(* package.CService.needsToBeAdvised(*))")
cService.needsToBeAdvised(cParam) //is still not intercepted
The only way it works is if I override needsTobeAdvised() in CService
Are all services in the same package? Given from your example code, I suspect AService and BService to be in the package package, but CService to be in another package. If services indeed are in different packages, you have some options:
Move so that they are in the same package
Change you pointcut to be more generic, e.g. "execution(* *.A+.needsToBeAdvised(*))
Add more pointcuts
Related
Is there a way to annotate just the class and have all the methods in the class create new spans? Basically, I am trying to get sleuth/spring to create new spans for all calls in a given repository class.
spring-boot version: '2.7.0'
Something like -
import org.springframework.cloud.sleuth.annotation.NewSpan;
#Newspan
public class ContactOperations{
public void doSomething(){
}
public void doSomethingElse(){
}
.....
}
Instead of
public class ContactOperations{
#Newspan
public void doSomething(){
}
#Newspan
public void doSomethingElse(){
}
.....
}
No this is not possible. The annotation NewSpan is only allowed on methods as you can see in the source code:
#Retention(value=RUNTIME)
#Inherited
#Target(value=METHOD)
public #interface NewSpan
I have a Service class that has a generic type and a setController method that is based on the same generic type. the generic type of the servic object is only known at the time of declaration.
The problem is now when i define a ControllerImpl where the generic type is defined the #Autowired method of setController does not use that component.
Has somebody an idea how to fix it and keep the ServiceImpl generic. (it would work when i define the typ in ServiceImpl as well).
The following example show the problem i'm facing with:
#SpringBootTest
#ActiveProfiles("local")
public class AccessTest {
#Autowired
private ServiceA<BeanA> service;
#Test
void test(){
Assertions.assertNotNull(service.controller);
}
interface ValueGetter{
}
static class BeanA implements ValueGetter{
}
static class AbstractService<B extends ValueGetter>{
Controller<B> controller;
#Autowired
void setController(#Nullable Controller<B> controller){
this.controller = controller;
}
}
interface Controller<B extends ValueGetter>{
void doSomething(B value);
}
//not inner class
#Service
public class ServiceA<B extends AccessTest.ValueGetter> extends AccessTest.AbstractService<B> {
}
//not inner class
#Component
public class ControllerImpl implements AccessTest.Controller<AccessTest.BeanA> {
#Override
public void doSomething(final AccessTest.BeanA value) {
}
}
}
I have a dummy project where I try figure out how to test pointcuts being triggered.
My project consists of 1 aspect bean which just prints after a foo method is called
#Component
#Aspect
public class SystemArchitecture {
#After("execution(* foo(..))")
public void after() {
System.out.println("#After");
}
}
And a FooServiceImpl with implemented foo method
#Service
public class FooServiceImpl implements FooService{
#Override
public FooDto foo(String msg) {
return new FooDto(msg);
}
}
The code works and and I can see "#After" being printed to console, but I can't check programatically if after pointcut was called using the test below.
#SpringBootTest
public class AspectTest {
#Autowired
private FooService fooService;
#Test
void shouldPass() {
fooService.foo("hello");
}
}
I've also tried using non-bean proxy as was adviced in https://stackoverflow.com/a/56312984/18224588, but this time I'm getting an obvious error cannot extend concrete aspect because my spy proxy is no longer viewed as an aspect:
public class AspectNoContextTest {
#Test
void shouldPass() {
FooService fooService = Mockito.mock(FooService.class);
SystemArchitecture systemArchitecture = Mockito.spy(new SystemArchitecture());
AspectJProxyFactory aspectJProxyFactory = new AspectJProxyFactory(fooService);
aspectJProxyFactory.addAspect(systemArchitecture);
DefaultAopProxyFactory proxyFactory = new DefaultAopProxyFactory();
AopProxy aopProxy = proxyFactory.createAopProxy(aspectJProxyFactory);
FooService proxy = (FooService) aopProxy.getProxy();
proxy.foo("foo");
verify(systemArchitecture, times(1)).after();
}
}
Ok, after some digging, I found that it's possible to accomplish this by making an aspect a #SpyBean. Also AopUtils can be used for performing additional checks
#SpringBootTest
public class AspectTest {
#Autowired
private FooService fooService;
#SpyBean
private SystemArchitecture systemArchitecture;
#Test
void shouldPass() {
assertTrue(AopUtils.isAopProxy(fooService));
assertTrue(AopUtils.isCglibProxy(fooService));
fooService.foo("foo");
verify(systemArchitecture, times(1)).after();
}
}
I have some Jpa repositories and several Entity class. I need to create a helper object for one of my Entity. Inside that helper I use #Autowire to access the Jpa repositories.
#Entity
class A {
#Transient
Helper helper;
...
}
class Helper {
A a;
#Autowired
CRepository repo;
public Helper(A a) {
this.a = a;
}
}
However, the repo is always null. I've tried using SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this) and #Configurable, but both of them failed. Can anybody provide some hint for me?
BTW, A is instantiated inside a rest controller.
Thanks!.
You can use a BeanUtil class to get any bean that created in Springl
#Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
Then you can get the bean.
MyBean obj = BeanUtil.getBean(MyBean.class);
Use constructor injection instead of field injection; this is a best practice all the time anyway. Then it's trivial to inject your A into the controller and pass it as a constructor argument.
#Configurable annotation works fine, but you need to use #EnableSpringConfigured annotation in any configuration class in order to make it work. Read my answer in other stackoverflow post: spring autowiring not working from a non-spring managed class
Entity class should not contain any helpers, even if transient. For a clean design you need to separate concerns, so the entity should not be aware of your business logic. I cannot help you more since I don't know which is the goal of that helper, but here you have other alternatives:
ALTERNATIVE 1 (based on your description seems that helper is an stateful bean, so it is not candidate to be a #Service, which I personally think it should be)
#Controller
public MyController {
#RequestMapping(...)
public void processRequest() {
A a = new A();
...
Helper helper = new Helper(a); // CRepository is successfully autowired
}
}
#Configurable(autowire = Autowire.BY_TYPE)
public class Helper {
A a;
#Autowired
CRepository repo;
}
#Configuration
#EnableSpringConfigured
public Application {
...
}
ALTERNATIVE 2 (make your Helper class stateless so that spring is aware of your beans without the need of extra stuff like #Confgurable/#EnableSpringConfigured)
#Controller
public MyController {
#Autowired Helper helper; // CRepository is correctly autowired
#RequestMapping(...)
public void processRequest() {
A a = new A();
...
helper.doSomething(a);
}
}
#Service
public class Helper {
// A a; remove dependency to A to make it stateless
#Autowired
CRepository repo;
public Helper() {
}
public void doSomething(A a) {
...
repo.save(a);
}
}
You cannot autowire nothing in your Helper class because it isn't managed by Spring.
You can use this approach:
public class HelperManager {
#Autowired
private ApplicationContext context;
public Helper getHelper(A a) {
return context.getBean(Helper.class, a);
}
Configure Helper to be a prototype bean:
#Configuration
public class MyConfiguration {
#Bean
public HelperManager helperManager() {
return new HelperManager();
}
#Bean
#Scope("prototype")
public Helper helper(A a) {
return new Helper(a);
}
}
And finally in your controller:
#Controller
public class MyController {
#Autowired
private HelperManager helperManager;
public someMethodWhereToInstanceYourHelper(A a) {
...
Helper helper = helperManager.getHelper(a);
...
}
}
Sorry: Google Traductor (english basic)
Interface implemented by aspect:
public interface MinReader {
void interceptThoughts();
}
MinReader class that implements the interface, which contains the "Aspect"
#Aspect
public class Magician implements MinReader {
#Pointcut("within(paquetea.paqueteb.*)")
public void thinking() {
}
#Override
#Before("thinking()")
public void interceptThoughts() {
// Codigo
}
}
This is a part of my JavaConfig:
#Configuration
#EnableAspectJAutoProxy
public class SpringIdolConfig {
#Bean
public MinReader magician() {
return new Magician();
}
// Otros bean
}
the problem is that the "interceptThoughts" method is never invoked.
My "solution" is to change the return type of method "magician" in my JavaConfig:
"MinReader" -> "Magician"
#Bean
public Magician magician() {
return new Magician();
}
Why is that?
Is there any way to use "MinReader" instead of "Magician"?
UPDATE: these are the other beans:
package paquetea.paqueteb;
public interface Thinker {
void thinkOfSomething(String thoughts);
}
package paquetea.paqueteb;
public class Volunteer implements Thinker {
#Override
public void thinkOfSomething(String thoughts) {
//code
}
}
This is my full javaconfig:
#Configuration
#EnableAspectJAutoProxy
public class SpringIdolConfig {
#Bean
public MinReader magician() {
return new Magician();
}
#Bean
public Thinker volunteer() {
return new Volunteer();
}
}
I'm guessing a bit, but I think one of your problems is that you've got the pointcut expression wrong. If I've read the examples in here right, you should use:
#Pointcut("within(paquetea.paqueteb..*)")
Note the ..*, and not the .* that you had. I find that when I get pointcuts wrong, they can be very difficult to debug, as their normal way of failing is to just silently not attach to anything. (My preferred technique is to attach to methods annotated with a custom annotation; that makes it easy to control what's happening and easy to debug.)