I thought I set up a spring bean so that when my web application context gets initialized the start method runs, but it isn't running. When I start my application in debug mode I never hit the breakpoint in the start method. Here's how I have the class set up:
@Transactional
@Service
public class ServerStartup implements Lifecycle {
@Autowired
private EmpireService es;
/**
* sets up the server the first time. Should only be called once
*/
private boolean setup() {
[... sets stuff up, saves the empire]
}
/**
* initializes the Empire with its necessary value
*/
@Override
public void start() {
Empire empire = es.getEmpire();
if (empire == null) {
//initialize all data as there is no "empire"
this.setup();
empire = es.getEmpire();
}
Empire.setEmpireGold(empire.getInstanceEmpireGold());
}
/**
* does nothing
*/
@Override
public void stop() {
}
/**
* does nothing
*/
@Override
public boolean isRunning() {
return false;
}
}
The reason I need to do this is that when my program starts up, it needs to check if a map has been built. If it hasn't, it needs to build one. Also, it is essentially setting up a cached value, the Empire's empireGold.
If there's a better, more efficient way to do this than implementing Lifecycle I'd be open to suggestions. Otherwise I just want this to work!
There is more than one way to instruct Spring to run some initialization logic after a bean has been created. My personal preference is to use the @PostConstruct
annotation, because it's a standard (defined in the javax.annotation
package) independent from Spring or any other container.
If you go for this solution and annotate your start()
method with @PostConstruct
, don't forget to include <context:annotation-config/>
in your configuration, otherwise it will be ignored.
See the Spring documentation on this annotation here .
For alternative solutions for the same problem check out the section on "Customizing the nature of a bean" .
使用@PostConstruct
注释您的start方法
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.