I am using the @Resource
annotation to inject an object which is working fine. However I would like to set an attribute on this injected object and I'm not sure whether this is possible using annotations.
For example, I have class Test
which has an instance of MyClass
injected using the @Resource
annotation. MyClass
has an attribute, myAttribute
, which I want to set when the MyClass
instance is injected.
Does anyone know if this is possible?
You should make use of the @PostConstruct
annotation, from javax.annotation
:
public class Test {
@Resource
private MyClass myClass;
@PostConstruct
public void init() {
myClass.setMyAttribute("test-class");
}
}
public class AnotherTest {
@Resource
private MyClass myClass;
@PostConstruct
public void init() {
myClass.setMyAttribute("another-test-class");
}
}
This method will then be called after Spring has initialised your object (ie all dependencies have been injected).
I'm assuming that MyClass
isn't a Singleton.
If you are sure that you won't have more than one dependency or alternative MyClass instances at runtime, you can use the solution by StuPointerException. But if both Test and AnotherTest exist in a single application context then due to the singleton default scope of spring beans the AnotherTest initialization will affect the state of Test as well.
This is because @Resource will inject the same bean into both owner beans.
To prevent this you should create different beans by the same class. This requires either xml configuration or JavaConfig. Since you favor annotations here it is:
@Configuration
public class AppConfig {
@Bean
public MyClass myClass1() {
MyClass myClass = new MyClass();
myClass.setMyAttribute("attr-value-1");
return myClass;
}
@Bean
public MyClass myClass2() {
MyClass myClass = new MyClass();
myClass.setMyAttribute("attr-value-2");
return myClass;
}
}
And then you can autowire with @Resource as before but with different beans in each case
public class Test {
@Resource("myClass1")
private MyClass myClass;
}
public class AnotherTest {
@Resource("myClass2")
private MyClass myClass;
}
DI with Spring :
@Autowired
MyClass myClass
With Java-ee :
@Inject
MyClass myClass
Concerning annotated property injection, you can still take a look at @Value
, but you'll need a properties file along with it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.