spring bean with dynamic constructor value

前端 未结 3 380
天命终不由人
天命终不由人 2020-12-05 03:26

I need to create an Object which is in-complete without the constructor argument. Something like this

Class A  {
  private final int timeOut
  public A(int t         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 04:00

    Two options spring (no pun intended) to mind:


    1. create a timeout factory, and use that as the constructor parameter. You can create a bean which implements FactoryBean, and it's job is to create other beans. So if you had something that generates salt's for encryption, you could have it return from getObject() a EncryptionSalt object. In your case you're wanting to generate Integers.

    Here is an example: http://www.java2s.com/Code/Java/Spring/SpringFactoryBeanDemo.htm


    2. create a timeout bean that wraps an int that's dynamically set, and leave that in the "prototype" state so it's created each time Instead of going to the hassle of creating a factory, the EncryptionSalt object could just be declared as a prototype bean, so when it's injected a new object is created each time. Place the logic into the constructor or somewhere else.


    It somewhat depends what value you want the timeout to actually be.

提交回复
热议问题