how to proxy an interface using spring like spring data jpa? - java

there is on interface and no implementation.
Interface Test{
#MyAnnotation
pubilc void sayHello();
}
and i want to using spring to proxy that and let it can be autowired in other beans ,like
Class App{
#Autowired
Test test;
}
and in some proxy class i will handle invoke of 'sayHello' by some custom actions according to its annotation .
so how to config the spring xml file and how to write some "MethodInvokeHandler" class ?
i want to add some configuration to spring xml and assign "base-package" to scan these interface and generate the auto proxy code into spring context , so i can use #autowired to inject them to other bean .

This function is no standard spring functionality, so you can not configurate, you have to implement it.
But Java supports you with the Dynamic Proxy API, and its core class Proxy.

Related

How to call Spring Framework repositories methods

I know that there are questions similar to this one, but none of them have helped me. I'm following along this tutorial, and the part I can't wrap my mind around is:
#SpringBootApplication
public class Application {
private static final Logger log =
LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
#Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
// save a couple of customers
...
// more lines, etc...
What I don't understand is where the repository passed into demo comes from. I know that the Autowired annotation can do something like that, but it isn't used at all here.
The more specific reason I ask is because I'm trying to adapt what they do here to an application I'm working on. I have a class, separate from all of the persistence/repository stuff, and I want to call repository methods like save and findAll. The issue is that the repository is an interface, so I can't instantiate an object of it to call the methods. So do I have to make a new class that implements the interface and create an object of that? Or is there an easier way using annotations?
When creating a #Bean, adding the repository in the parameters of the bean is enough to wire the repos in your bean. This works pretty much like adding #Autowired annotation inside a class that is annotated as #Component or something similar.
Spring works mostly with interface, since that is simplier to wire vs wiring concrete classes.
Can you try #Repository before the declaration of class? Worked for me in a Spring MVC structure.
#Repository
public class EntityDAOImpl implements EntityDAO{
...
}
The thing to wrap your head around is a Spring Boot application at startup time aims to resolve its dependancy tree. This means discovering and instantiating Beans that the application defines, and those are classes annotated with #Service, #Repository, etc.
This means the default constructor (or the one marked with #Autowire) of all beans is invoked, and after all beans have been constructed the application starts to run.
Where the #Bean annotation comes into play is if you have a bean which does not know the values of it's constructor parameters at compile time (e.g. if you want to wire in a "started at" timestamp): then you would define a class with an #Configuration annotation on it, and expose an #Bean method in it, which would return your bean and have parameters that are the beans dependencies. In it you would invoke the beans constructor and return the bean.
Now, if you want a certain method of some class to be invoked after the application is resolved, you can implement the CommandLineRunner interface, or you can annotate a method with #PostConstruct.
Some useful links / references:
https://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html
https://www.baeldung.com/spring-inject-prototype-bean-into-singleton
Running code after Spring Boot starts
Execute method on startup in Spring

Equivalent of javax.enterprise.inject.Instance in Spring Boot for dynamic injection

I'm migrating code from JEE to SpringBoot. I was using cool dynamic injection in JEE with javax.enterprise.inject.Instance class:
Just annotating:
#Inject
private Instance<CCIntentHandler> allMycandidates;
Will make allMycandidates be filled with all classes inheriting CCIntentHandler interface in my classpath which then I can iterate simply with:
Iterator<CCIntentHandler> iterator = allMycandidates.iterator()
Nothing more needed. How can I achieve this in Spring Boot?
Thanks
Spring will inject all instances of Foo if you #Autowire a List<Foo>.
So, the Spring equivalent of ...
#Inject
private Instance<CCIntentHandler> allMycandidates;
... is:
#Autowire
private List<CCIntentHandler> allMycandidates;
Update 1 in response to this comment:
Do CCIntentHandler interface or classes implementing this interface need any Spring annotations?
Spring must be aware of any instances of CCIntentHandler, this could achieved as follows:
Annotate each class implementing CCIntentHandler with #Component and ensure that these classes are scanned by Spring Boot
Or
Provide a public method to return each class implementing CCIntentHandler and annotate each of these public methods with #Bean and ensure that the class which contains these public methods is annotated with #Configuration and that this configuration class is scanned by Spring Boot.
More details on bean declaration and dependency injection in the docs.
Unfortunately
#Autowire
private List<CCIntentHandler> allMycandidates;
is not
#Inject
private Instance<CCIntentHandler> allMycandidates;
because we can't select an instance from the list depending on type or annotation.
I've spent some time to find alternative in Spring, but looks like there is no equivalent...
We should defenetly bring that feature to Spring!

Injecting Spring Data Repository into arbitrary classes

I have created a few interfaces extending CrudRepository. I'd like to use them into a generic class that is not a bean. What I do currently is to inject them using #Autowired inside my RestController and then pass them down as method arguments to this generic class I'm talking about. Is there a better way to achieve this?
One approach is to make your unmanaged class extending SpringBeanAutowiringSupport and use #Autowired properties. If your application has a Spring web application context, it can then try to get the context from the current thread and resolve the #Autowired properties for you.

How to create RESTful service with customizable notification in spring boot

I'm new to spring, but not new to java.
I'd like to create base class for all REST services that would send notification through some messaging protocol on requests with chosen methods (POST, PUT, PACTCH) (when resource is changed basically)
So for example If I would create interface
public interface RestService<T, I> {
T get(I id);
T create();
T patch(I id);
T put(I id);
}
How can I use that in spring RestController and somehow decorate it with notifications?
All this spring #Autowire and configuration files is somewhat confusing to me, because while I'm familiar with dependency injection and used constructor dependency injection I haven't used IOC much.
I believe that the best option for you will be to use Spring AOP and put some annotation to the required methods. Please check this:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
You can use any interface or base class for any restcontroller or for any other Spring stereotype. The annotations are just clues for Spring itself to use the class as an endpoint for a rest service for example. Your class otherwise can be anything, like:
#RestController
class MyController {
#Autowired
private MyService myService; //If you use the spring sterotypes you dont need to do anything to use a bean but just to use the autowired annotation
}
#RestController
class AnyotherController extends AbstractController {...}
#RestController
class YetAnotherController extends AbstractController implements Something {}
Are all valid resources (i.e. web-components) for Spring to use.

Implementing Dependency Injection using Custom Annotation

I am working on a core java framework. I don't want to create instances directly inside the class which is why I want to use dependency injection.
I am thinking of declaring my custom annotations on the fields to be instantiated. And having a call back function which would create an instance and inject it into the field.
I had tried to create a custom annotation. But looks like there's no direct way to get a callback on the declared annotation. So, I was trying to scan the classes for that. But I ended up with this problem
Java Scanning Class for Annotation using Google Reflections
Please let me know if this is the right way of achieving this.
Since your question is tagged 'Spring', you can use Spring Framework's bean annotations (#Component / #Service / #Repository / ...), classpath scanning and #Autowired.
For example:
Setup classpath scanning on your spring config xml:
<context:component-scan base-package="com.mycompany.myapp" />
Create your bean to be scanned. Spring container will automatically create a singleton instance of this bean using default constructor:
#Repository
public class FooDAO {
...
}
Inject reference to above DAO instance using DI + autowiring
#Service
public class FooService {
#Autowired private FooDAO fooDAO;
...
}

Categories

Resources