skumar
skumar

Reputation: 1015

Spring inject property values from a bean into another bean

Have 2 java beans in my spring boot project. First bean gets the values from property file (spring injected) and second bean gets the values from different source.

After spring initialize, I want to merge the property values from second bean into first bean. Please let know if spring provides any class to dynamically inject the values.

first bean gets the values from property file:
----------------------------------------------
@value("username")
private String username
@Value("server")
private String servername
@Value("inject from second bean")
private String location
@Value("inject from second bean")
private boolean enabled

second bean gets the values from different source
-----------------------------------------------
private String location
private boolean enabled

Upvotes: 2

Views: 2674

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

Try using the expression langugage:

@Value(#{anotherBean.location})
private String location
@Value(#{anotherBean.enabled})
private boolean enabled

Update

Alternatively you can assign that in the post construct:

@Autowired
private AnotherBean anotherBean;

@PostConstruct
public void init(){
    location = anotherBean.getLocation();
    enabled = anotherBean.isEnabled();
}

Update 2

The last thing that comes to my mind that could work out of the box is changing the scope of the first bean to prototype instead of singleton:

@Scope("prototype")

Now everytime this bean would used (getBean on spring context for example) a new instance would be created.. and everytime fresh data from anotherBean wouuld be injected.

But this is specific so you would have to think whether this scenario fits your application.

Upvotes: 1

Related Questions