I would like to create my own custom annotation. My framework is stand alone Java application. When someone annotate his pojo class a "hidden" code behind will trigger methods.
For example, today in Java EE we have #MessageDriven annotation.
And when you annotate your class with #MessageDriven and in addition implement MessageListener Interface there is a behind code that will trigger onMessage(Message msg). when a message arrives from a Queue/Topic.
How do I create an annotation (#MyMessageDriven) which could be added to a pojo and also implement MyCustomMessageListener.
The result which I desire is a trigger of "hidden" code (of mine) which will trigger a method of an implemented interface (exactly as it works with the sample i Wrote below).
I recommend to read this blog entry (snapshot on archive.org) up to the point where the author remembers (s)he has access to Spring's component scan feature.
The initial issue is to scan the class path to find classes with the custom annotation. Once this is done, you have the objects in your standalone application through which using object.getClass().getAnnotations(), you can then inject the listeners or custom behavior you need to add to the objects holding the custom annotations.
Let's say you have the following custom annotation:
#Target({ ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
public #interface MyMessageDriven {}
And you use it some class in you application:
#MyMessageDriven
public class MyObject {}
Now, in the appropriate location in your application, you should have a method to give out all classes carrying MyMessageDriven:
Set<Class<?>> findAllMessageDrivenClasses() {
final StopWatch sw = new StopWatch();
sw.start();
final Reflections reflections = new Reflections("org.projectx", new TypeAnnotationsScanner());
Set<Class<?>> allMessageDrivens = reflections.getTypesAnnotatedWith(MyMessageDriven.class); // NOTE HERE
sw.stop();
return allMessageDrivens;
}
Having this, I assume that there is a point in your application that either (1) you have access to the objects in your application, or (2) there is a visitor or iterator pattern on all the objects in the application. So, in some point, I assume that we have all targeted objects as objects:
Set<Class<?>> msgDrivenClasses = findAllMessageDrivenClasses();
for (Object o : objects) {
if (msgDrivenClasses.contains(o.getClass()) {
invokeTheMessageListener(o);
}
}
On the other hand, there should be some implementation of MyMessageListener that is available when the objects having MyMessageDriven are found:
void invokeTheMessageListener(Object o) {
theMessageListener.onMessage(o);
}
This answer is tailored from the blog entry so please refer to the blog for configuration of libraries. And, last but not least, this is a sample code for the problem and it can be refactored to more pattern-compatible and elegant style.
Update: There is a requirement that the targeted objects should be aware of their own listeners. So, I'd suggest the following approach. Let's have an interface MyMessageListenerAware:
interface MyMessageListenerAware {
MyMessageListener getMyMessageListener();
}
// and this is the original MyMessageListener
interface MyMessageListener {
void onMessage(Object o);
}
Now, the target objects should implement the above interface:
class MySampleObject implements MyMessageListenerAware {
public MyMesssageListener getMyMessageLisener() {
return mySampleObjectImplementationOfMyMessageListener;
}
}
Having this, the method invokeTheMessageListener becomes like:
void invokeMessageListener(Object o) {
if (o instance MyMessageListenerAware) {
MyMessageListener l = ((MyMessageListenerAware) o).getMyMessageListener();
l.onMessage(o);
}
}
Although, I strongly recommend reading about Visitor or Strategy pattern. What you aim to do seems to me like you need certain objects react/act/process to a common object/event in the application but each with their own interpretation/algorithm/implementation.
create an annotation something like this:
public #interface MyMessageDriven{
}
And you have an interface that can apply annotation like this:
public interface MyMessagListener {
public void message();
}
#MyMessageDriven
public class MyMessage implements MyMessagListener {
public void message(){
System.out.println(" I am executed")
}
}
Load the above class using classloader and using reflections check the annotation is presrent.
if it is present, use loaded instance to execute it.
Object obj = ClassLoader.getSystemClassLoader().loadClass("MyMessage").newInstance();
MyMessagListener mml = (MyMessagListener) obj;
mml.message();
Listener implementation you can put in MyMessage class or some other class that implements MessageListener.
In this case, need to provide implementation for message() what it is going to do.
But this class should be loaded and more important thing here is how your MyMessage class is loaded.
That is based on the meta data present in the MyMessage class.Similar way, in the real time scenario as well this is how it works.
Annotation is a metadata to a class that says based on the supplied data, do something.Had this metadata not present in the MyMessage class, you need not execute message() method.
Hope this will help you.
Related
I would like to create my own custom annotation. My framework is stand alone Java application. When someone annotate his pojo class a "hidden" code behind will trigger methods.
For example, today in Java EE we have #MessageDriven annotation.
And when you annotate your class with #MessageDriven and in addition implement MessageListener Interface there is a behind code that will trigger onMessage(Message msg). when a message arrives from a Queue/Topic.
How do I create an annotation (#MyMessageDriven) which could be added to a pojo and also implement MyCustomMessageListener.
The result which I desire is a trigger of "hidden" code (of mine) which will trigger a method of an implemented interface (exactly as it works with the sample i Wrote below).
I recommend to read this blog entry (snapshot on archive.org) up to the point where the author remembers (s)he has access to Spring's component scan feature.
The initial issue is to scan the class path to find classes with the custom annotation. Once this is done, you have the objects in your standalone application through which using object.getClass().getAnnotations(), you can then inject the listeners or custom behavior you need to add to the objects holding the custom annotations.
Let's say you have the following custom annotation:
#Target({ ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
public #interface MyMessageDriven {}
And you use it some class in you application:
#MyMessageDriven
public class MyObject {}
Now, in the appropriate location in your application, you should have a method to give out all classes carrying MyMessageDriven:
Set<Class<?>> findAllMessageDrivenClasses() {
final StopWatch sw = new StopWatch();
sw.start();
final Reflections reflections = new Reflections("org.projectx", new TypeAnnotationsScanner());
Set<Class<?>> allMessageDrivens = reflections.getTypesAnnotatedWith(MyMessageDriven.class); // NOTE HERE
sw.stop();
return allMessageDrivens;
}
Having this, I assume that there is a point in your application that either (1) you have access to the objects in your application, or (2) there is a visitor or iterator pattern on all the objects in the application. So, in some point, I assume that we have all targeted objects as objects:
Set<Class<?>> msgDrivenClasses = findAllMessageDrivenClasses();
for (Object o : objects) {
if (msgDrivenClasses.contains(o.getClass()) {
invokeTheMessageListener(o);
}
}
On the other hand, there should be some implementation of MyMessageListener that is available when the objects having MyMessageDriven are found:
void invokeTheMessageListener(Object o) {
theMessageListener.onMessage(o);
}
This answer is tailored from the blog entry so please refer to the blog for configuration of libraries. And, last but not least, this is a sample code for the problem and it can be refactored to more pattern-compatible and elegant style.
Update: There is a requirement that the targeted objects should be aware of their own listeners. So, I'd suggest the following approach. Let's have an interface MyMessageListenerAware:
interface MyMessageListenerAware {
MyMessageListener getMyMessageListener();
}
// and this is the original MyMessageListener
interface MyMessageListener {
void onMessage(Object o);
}
Now, the target objects should implement the above interface:
class MySampleObject implements MyMessageListenerAware {
public MyMesssageListener getMyMessageLisener() {
return mySampleObjectImplementationOfMyMessageListener;
}
}
Having this, the method invokeTheMessageListener becomes like:
void invokeMessageListener(Object o) {
if (o instance MyMessageListenerAware) {
MyMessageListener l = ((MyMessageListenerAware) o).getMyMessageListener();
l.onMessage(o);
}
}
Although, I strongly recommend reading about Visitor or Strategy pattern. What you aim to do seems to me like you need certain objects react/act/process to a common object/event in the application but each with their own interpretation/algorithm/implementation.
create an annotation something like this:
public #interface MyMessageDriven{
}
And you have an interface that can apply annotation like this:
public interface MyMessagListener {
public void message();
}
#MyMessageDriven
public class MyMessage implements MyMessagListener {
public void message(){
System.out.println(" I am executed")
}
}
Load the above class using classloader and using reflections check the annotation is presrent.
if it is present, use loaded instance to execute it.
Object obj = ClassLoader.getSystemClassLoader().loadClass("MyMessage").newInstance();
MyMessagListener mml = (MyMessagListener) obj;
mml.message();
Listener implementation you can put in MyMessage class or some other class that implements MessageListener.
In this case, need to provide implementation for message() what it is going to do.
But this class should be loaded and more important thing here is how your MyMessage class is loaded.
That is based on the meta data present in the MyMessage class.Similar way, in the real time scenario as well this is how it works.
Annotation is a metadata to a class that says based on the supplied data, do something.Had this metadata not present in the MyMessage class, you need not execute message() method.
Hope this will help you.
First, please let me introduce a minimal scene demo to explain the problem.
Let's say i have a strategy pattern interface.
public interface CollectAlgorithm<T> {
public List<T> collect();
}
And a implementation of this strategy, the ConcreteAlgorithm.
public class ConcreteAlgorithm implements CollectAlgorithm<Integer> {
#Resource
QueryService queryService;
#Override
public List<Integer> collect() {
// dummy ...
return Lists.newArrayList();
}
}
As you can see, the implementation depend on some query operation provided by a #Service component.
The ConcreteAlgorithm class will be created by new in some places, then the collect method will be called.
I've read some related link like Spring #Autowired on a class new instance, and know that the above code cannot work, since the instance created by new has a #Resource annotated member.
I'm new to Spring/Java, and i wonder if there are some ways, or different design, to make scene like above work.
I've thought about use factory method, but it seems that it will involve many unchecked type assignment since i provided a generic interface.
UPDATE
To make it more clear, i add some detail about the problem.
I provide a RPC service for some consumers, with an interface like:
public interface TemplateRecommendService {
List<Long> recommendTemplate(TemplateRecommendDTO recommendDTO);
}
#Service
public class TemplateRecommandServiceImpl implements TemplateRecommendService {
#Override
public List<Long> recommendTemplate(TemplateRecommendDTO recommendDTO) {
TemplateRecommendContext context = TemplateRecommendContextFactory.getContext(recommendDTO.getBizType());
return context.process(recommendDTO);
}
}
As you can see, i will create different context by a user pass field, which represent different recommendation strategy. All the context should return List<Long>, but the pipeline inside context is totally different with each other.
Generally there are three main stage of the context process pipeline. Each stage's logic might be complicated and varied. So there exists another layer of strategy pattern.
public abstract class TemplateRecommendContextImpl<CollectOut, PredictOut> implements TemplateRecommendContext {
private CollectAlgorithm<CollectOut> collectAlgorithm;
private PredictAlgorithm<CollectOut, PredictOut> predictAlgorithm;
private PostProcessRule<PredictOut> postProcessRule;
protected List<CollectOut> collect(TemplateRecommendDTO recommendDTO){
return collectAlgorithm.collect(recommendDTO);
}
protected List<PredictOut> predict(TemplateRecommendDTO recommendDTO, List<CollectOut> predictIn){
return predictAlgorithm.predict(recommendDTO, predictIn);
}
protected List<Long> postProcess(TemplateRecommendDTO recommendDTO, List<PredictOut> postProcessIn){
return postProcessRule.postProcess(recommendDTO, postProcessIn);
}
public /*final*/ List<Long> process(TemplateRecommendDTO recommendDTO){
// pipeline:
// dataCollect -> CollectOut -> predict -> Precision -> postProcess -> Final
List<CollectOut> collectOuts = collect(recommendDTO);
List<PredictOut> predictOuts = predict(recommendDTO, collectOuts);
return postProcess(recommendDTO, predictOuts);
}
}
As for one specific RecommendContext, its creation likes below:
public class ConcreteContextImpl extends TemplateRecommendContextImpl<GenericTempDO, Long> {
// collectOut, predictOut
ConcreteContextImpl(){
super();
setCollectAlgorithm(new ShopDecorateCrowdCollect());
setPredictAlgorithm(new ShopDecorateCrowdPredict());
setPostProcessRule(new ShopDecorateCrowdPostProcess());
}
}
Instead od using field oriented autowiring use constructor oriented one - that will force the user, creating the implementation instance, to provide proper dependency during creation with new
#Service
public class ConcreteAlgorithm implements CollectAlgorithm<Integer> {
private QueryService queryService;
#Autowired // or #Inject, you cannot use #Resource on constructor
public ConcreteAlgorithm(QueryService queryService) {
this.queryService = queryService;
}
#Override
public List<Integer> collect() {
// dummy ...
return Lists.newArrayList();
}
}
There are 4 (+1 Bonus) possible approaches I can think of, depending on your "taste" and on your requirements.
1. Pass the service in the constructor.
When you create instances of your ConcreteAlgorithm class you provide the instance of the QueryService. Your ConcreteAlgorithm may need to extend a base class.
CollectAlgorithm<Integer> myalg = new ConcreteAlgorithm(queryService);
...
This works when the algorithm is a stateful object that needs to be created every time or, with some variations, when you actually don't know the algorithm at all as it comes from another library (in which case you might have a factory or, in rare cases which most likely don't fit your scenario, create the object through reflection).
2. Turn your algorithm into a #Component
Annotate your ConcreteAlgorithm with the #Component annotation and then reference it wherever you want. Spring will take care of injecting the service dependency when the bean is created.
#Component
public class ConcreteAlgorithm implements CollectAlgorithm<Integer> {
#Resource
QueryService queryService;
....
}
This is the standard and usually preferred way in Spring. It works when you know ahead of time what all the possible algorithms are and such algorithms are stateless.
This is the typical scenario. I don't know if it fits your needs but I would expect most people to be looking for this particular option.
Note that in the above scenario the recommendation is to use constructor-based injection. In other words, I would modify your implementation as follows:
#Component
public class ConcreteAlgorithm implements CollectAlgorithm<Integer> {
final QueryService queryService;
#Autowired
public ConcreteAlgorithm(QueryService queryService) {
this.queryService = queryService;
}
#Override
public List<Integer> collect() {
// dummy ...
return Lists.newArrayList();
}
}
On the most recent versions of Spring you can even omit the #Autowired annotation.
3. Implement and call a setter
Add a setter for the QueryService and call it as needed.
CollectAlgorithm<Integer> myalg = new ConcreteAlgorithm();
myalg.setQueryService(queryService);
...
This works in scenarios like those of (1), but lifts you from the need of passing parameters to the constructor, which "may" help getting rid of reflection in some cases.
I don't endorse this particular solution however as it forces to know that you have to call the setQueryService method prior to invoking other methods. Quite error-prone.
4. Pass the QueryService directly to your collect method.
Possibly the easiest solution.
public interface CollectAlgorithm<T> {
public List<T> collect(QueryService queryService);
}
public class ConcreteAlgorithm implements CollectAlgorithm<Integer> {
#Override
public List<Integer> collect(QueryService queryService) {
// dummy ...
return Lists.newArrayList();
}
}
This works well if you want your interface to be a functional one, to be used in collections.
Bonus: Spring's SCOPE_PROTOTYPE
Spring doesn't only allow to instantiate singleton beans but also prototype beans. This effectively means it will act as a factory for you.
I will leave this to an external example, at the following URL:
https://www.boraji.com/spring-prototype-scope-example-using-scope-annotation
This "can" be useful in specific scenarios but I don't feel comfortable recommending it straight away as it's significantly more cumbersome.
We have multiple external variables in application.yml in spring boot application and i want to access this variable from my java code and based on the field value I want to redirect the call to various functions.
Example:
String externalVariable1 abc;
String externalVariable2 xyz;
method: if(string == abc) {
call function1; }
else {
call function2; }
Now problem here is there might be further addition to external variable in furture, I want to write robust method which should be adaptable to future addition to external variable without changing my core code. i might add the functionality as part of helper methods.
All I can think of reflection way, Can you guys help me with better approach given i am using spring boot application.
Don't do reflection for this. Instead, wrap function1/function2 into some kind of strategy object:
interface Strategy {
void doStuff();
}
class Function1 implements Strategy {
void doStuff() {
function1();
}
}
class Function2 implements Strategy {
void doStuff() {
function2();
}
}
Then, register all of these with some factory-style class:
class StrategyFactory {
private Strategy defaultStrategy = new Function2();
Map<String, Strategy> strategies = ....
strategies.put("abc", new Function1());
...
Strategy getStrategy(String key) {
return strategies.getOrDefault(key, defaultStrategy);
}
}
Finally, use it:
factory.getStrategy(valueFromYaml).doStuff();
Make key a more complex object than just String if you need to accommodate for more complicated scenarios, or use a more sophisticated way of selecting a strategy than a map lookup.
If you don't know the available strategies before runtime (e.g. if the configuration for these comes from a DB or files) keep only the class name of the Strategy implementation in a map:
Map<String, String> strategyClassNames = ...;
strategy.put(keyFromDB, valueFromDB);
...
and use it by:
Class<? extends Strategy> strategy = Class.forName(strategyClassNames.get(key));
strategy.newInstance().doStuff();
I am developing a framework which allows developers to do database operations through service layer. Service classes will send the database request dto object which will be annotated with sql ID to use as ID in MyBatis. Later I will read the annotation value by reflection.
First of all, I created a custom annotation interface.
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface MyBatisMapper {
String namespace() default "";
String sqlId() default "";
}
And interface for database request dto object.
public interface IReqDto {
public String getDaoType();
}
And database request dto object which will implement the above IReqDto interface.
#MyBatisMapper(namespace="User", sqlId="userInsert")
public class UserInsertReqDto implements IReqDto{
//beans and getters/setters
}
The above bean may vary as requirement of the developer. This is not part of the framework. Developer must implement IReqDto interface in any kind of database request object he use.
What I am trying is to read the annotated values (namespace and sqlId) from database invoker class by using reflection.
I understand that I can get the annotated value by doing this.
Class<UserInsertReqDto> ReqDto = UserInsertReqDto.class;
for(Annotation annotation : ReqDto.getAnnotations()) {
System.out.println(annotation.toString());
}
But my problem is, as the UserInsertReqDto will vary, I tried to use reflection to IReqDto interface.
Class<IReqDto> ReqDto = IReqDto.class;
Well, surely it doesn't work.
The question is - how can I read the annotated value from database request object in this situation? Thanks.
Maybe I'm still misunderstanding your question, so correct me if necessary.
You will be given an object of a custom implementation of ReqDto
ReqDto object = ...; // get instance
Class<?> clazz = object.getClass(); get actual type of the instance
for(Annotation annotation : clazz.getAnnotations()) { // these are class annotations
System.out.println(annotation.toString());
}
or
MyBatisMapper mapperAnnotation = clazz.getAnnotation(MyBatisMapper.class);
if (mapperAnnotation != null) {
System.out.println(mapperAnnotation.namespace()
System.out.println(mapperAnnotation.sqlId()
}
Reflection works regardless of the type. So, instead of referring to the concrete class, simply use Object#getClass() and/or Class<?>. E.g.
public Metadata getMetadata(Object pojo) {
Annotation annotation = pojo.getAnnotation(MyBatisMapper.class);
if (annotation == null) {
return null;
}
return new Metadata(annotation.getNamespcae(), annotation.getSqlId());
}
where Metadata is just a value class that you can use later on that contains the values about the object. You can also directly work with the MyBatisWrapper annotation.
I'm trying to make an application extensible by using CDI, but it seems like I'm missing a piece of the puzzle.
What I want:
Have a global configuration that will define which implementation of an interface to use. The implementations would have annotations like #ImplDescriptor(type="type1").
What I tried:
#Produces
public UEInterface createUserExit(#Any Instance<UEInterface> instance, InjectionPoint ip) {
Annotated annotated = ip.getAnnotated();
UESelect ueSelect = annotated.getAnnotation(UESelect.class);
if (ueSelect != null) {
System.out.println("type = " + ueSelect.type());
}
System.out.println("Inject is ambiguous? " + instance.isAmbiguous());
if (instance.isUnsatisfied()) {
System.out.println("Inject is unsatified!");
return null;
}
// this would be ok, but causes an exception
return instance.select(ueSelect).get();
// or rather this:
for (Iterator<UEInterface> it = instance.iterator(); it.hasNext();) {
// problem: calling next() will trigger instantiation which will call this method again :(
UEInterface candidate = it.next();
System.out.println(candidate.getClass().getName());
}
}
This code is close to an example I've seen: The #Produces method will be used to select and create instances and a list of candidates is injected as Instance<E>. If the method simply creates and returns an implementation, it works fine. I just don't know how to examine and select a candidate from the Instance<E>. The only way of looking the the "contents" seems to be an Iterator<E>. But as soon as I call next(), it will try to create the implementation... and unfortunately, calls my #Produces method for that, thereby creating an infinite recursion. What am I missing? How can I inspect the candidates and select one? Of course I want to instantiate only one of them...
Thanks in advance for any help and hints!
I think the issue is you are trying to select the annotation's class rather than using the annotation as a selector qualifier. Using the class directly searches for an implementation that implements that class. You need to create an AnnotationLiteral using the #ImplDescriptor class to perform a select using it as a qualifier. Create a class extending AnnotationLiteral like so.
public class ImplDescriptorLiteral extends AnnotationLiteral<ImplDescriptor> implements ImplDescriptor {
private String type;
public ImplDescriptorLiteral(String type) {
this.type = type;
}
#Override
public String type() {
return type;
}
}
then you can pass an instance of this class to the select method using the type you want.
instance.select(new ImplDescriptorLiteral("type1")).get();
Refer to the Obtaining a contextual instance by programmatic lookup documentation for more information.
Finch, what you have here should work. it assumes though that you have an instance of UEInterface that is annotated #UESelect, e.g.
#UESelect("one")
public class UEOne implements UEInterface {
..
}
Is this how you're expecting it to work?