Siempre que me encuentro haciendo una nueva aplicación en Spring en algún momento en el tiempo empiezo a requerir de un estado inicial para que esta funcione. En Grails es bien fácil manejar esto, solo lo metes en el Bootstrap.groovy y listo. ¿Pero en una aplicación con Spring cómo lo hago? Aquí está una posible solución.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package edu.swau.forms.utils; | |
import edu.swau.forms.dao.RoleDao; | |
import edu.swau.forms.dao.UserDao; | |
import edu.swau.forms.model.Role; | |
import edu.swau.forms.model.User; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.ApplicationListener; | |
import org.springframework.context.event.ContextRefreshedEvent; | |
import org.springframework.transaction.annotation.Transactional; | |
/** | |
* | |
*/ | |
public class Bootstrap implements ApplicationListener<ContextRefreshedEvent> { | |
private static final Logger log = LoggerFactory.getLogger(Bootstrap.class); | |
@Autowired | |
private RoleDao roleDao; | |
@Autowired | |
private UserDao userDao; | |
@Override | |
@Transactional | |
public void onApplicationEvent(ContextRefreshedEvent e) { | |
log.info("Validating roles"); | |
log.debug("Looking for {}", Constants.ROLE_ADMIN); | |
Role adminRole = roleDao.get(Constants.ROLE_ADMIN); | |
if (adminRole == null) { | |
adminRole = new Role(Constants.ROLE_ADMIN, 1); | |
roleDao.create(adminRole); | |
} | |
log.debug("Looking for {}", Constants.ROLE_USER); | |
Role userRole = roleDao.get(Constants.ROLE_USER); | |
if (userRole == null) { | |
userRole = new Role(Constants.ROLE_USER, 10); | |
roleDao.create(userRole); | |
} | |
log.info("Validating users"); | |
// TODO: Well, you get the idea... right? | |
log.info("Forms Application is up"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<bean id="bootstrap" class="edu.swau.forms.utils.Bootstrap" /> |
Comentarios