Order of constructor calls in Spring Boot

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月14日 18:43:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63411230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定