Reputation: 73
I have utility method which takes string as input parameter and gives me an object corresponding to input. I need to call this utility method from Spring boot request mapping method.
Now my question is what are the advantages and disadvantages of below two approaches ?.
Sample code for approach 1 :
**//SourceSystem can change at runtime**
public static FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
Sample code for approach 2 :
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
PS : Samples collected from other post.
Upvotes: 0
Views: 939
Reputation: 8758
If you already use Spring then choose singleton (one object of bean per instance of Spring container) bean (which is the default scope) which is OK if your static method doesn't have any shared state. If you choose prototype then Spring container will return new instance of bean object for each getBean()
call. And inject that bean to objects which need to call that method. This approach is also more unit-test friendly than static method because you can provide test implementation of bean with such method in test application context. In case of static methid you will need PowerMock or other 3rd party libraries to mock stick method for unit testing.
UPDATE
In your case there should be new bean
@Service
public MyReportBeanFactory {
@Autowired
private Dao dao;
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
And then you need to inject this factory bean into classes where you want to call fixedLengthReport()
Upvotes: 1