Issue
I am wondering whether @PostConstruct method is ever called when a static method from a component is called for e.g.
@Component
public class SomeComponent{
@Autowired
private SomeService someService;
@Autowired
private CacheManager cacheManager;
private static SomeService someService;
private static CacheManager cacheManager;
@PostConstruct
void init(){
SomeComponent.someService = someService;
SomeComponent.cacheManager= cacheManager;// set up static variables
};
SomeComponent{};
public static List<MyObjectDTO> someStaticMethod (){
List<MyObjectDTO> returnList = new ArrayList<MyObjectDTO>();
returnList = getCacheList();
.
.
//does some more manipulation to that list
return returnList;
}
private static List<MyObjectDTO> getCacheList() {
SomeComponent someComponent = new someComponent();
return someComponent.setAndGetCachedList();
}
private List<MyObjectDTO> setAndGetCachedList (){
ModelMapper modelMapper = new ModelMapper();
someService.getList(); //sets the cache first
Cache cache = cacheManager.getCache("MyCache");
Type list = new TypeToken<List<MyObjectDTO>>(){}.getType();
List<MyObjectDTO> cacheList = modelMapper.map(cache.get(SimpleKey.EMPTY).get(), list)); //maps the cached list to list of MyObjectDTO
return cacheList;
};
}
@Service
public class SomeService{
public method(){
SomeComponent.someStaticMethod(); //is @PostConstructor called here?
}
}
Is @PostConstructor method ever called when the static method of the component is called above? If not, in what way can the @PostConstructor method be called? Much thanks!
Solution
No, @PostConstruct
can not be applied to a static method. The whole point of this annotation is to be called on a method of a Bean after the bean has been constructed. In the case of a static method, there is no corresponding Bean (Java object) and so it doesn't make sense to have a static @PostConstruct
method.
Answered By - CryptoFool
Answer Checked By - Willingham (JavaFixing Volunteer)