Reputation: 7228
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.
Upvotes: 1
Views: 1503
Reputation: 41113
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;
...
}
Upvotes: 1