英文:
Order of constructor calls in Spring boot
问题
我有一个用@Service
注解的ServiceClass
类,在其中对一个对象进行构造函数注入。
@Service
public class ServiceClass
{
Dog dog;
@Autowired
public ServiceClass(Dog dog) {
this.dog = dog;
}
}
现在我还需要添加一些配置代码,这些代码应该在ServiceClass
内部的任何其他方法调用之前只运行一次。
我考虑创建一个无参构造函数,并将配置放在其中,但是Spring不会调用该构造函数。
我应该将其放在进行注入的构造函数中,还是有其他方法可以实现这一点。
英文:
I have a class ServiceClass
annotated with @Service
, inside that I do constructor injection for an object.
@Service
public class ServiceClass
{
Dog dog;
@Autowired
public ServiceClass(Dog dog) {
this.dog = dog;
}
}
Now I also need to add some configuration code, that should run just once and prior to any other method call inside ServiceClass
.
I thought of creating a no arg constructor and put those configuration inside those, but spring doesn't call that constructor.
Should I put it inside constructor where I do injection, or is there some other way to achieve it.
答案1
得分: 1
在这种情况下,有两个适用的选择,可以在不在构造函数中实现初始化逻辑的情况下进行选择。
第一个选择是使用 @PostConstruct 注解,在其中定义配置逻辑。另一个选择是让你的 ServiceClass 实现 InitializingBean 接口,并将配置逻辑放在 afterPropertiesSet 方法中。
英文:
There are in this case two suitable options to go for without implementing the initialization logic in your constructor.
The First one is an @PostConstruct where you define your configuration logic. Another option would be to let your ServiceClass implement the InitializingBean interface and put this configuration logic in your afterPropertiesSet method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论