在编程SSH项目时,可能要写一个Installer类来初始化数据库,一般的编写方式如下
@Component
public class Installer {
@Resource
protected RoleService roleService;
@Resource
protected UserService userService;
@Resource
protected PrivilegeService privilegeService;
@Resource
private SessionFactory sessionFactory;
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Installer installer = (Installer) ac.getBean("installer");
System.out.println("-- 安装开始 --");
installer.install();
System.out.println("-- 安装完毕 --");
}
@Transactional
public void install() {
//调用roleService/userService/privilegeService初始化数据库
}
}
这种方式的优点是可以直接使用 @Resource 注入的类,但是使用这种方式必须注意亮点:1、Installer类必须有@Component注解(声明该类交由spring管理,这样spring才会对他内部的@Resource注解的变量进行注入);2、程序必须由main中启动,如果使用单元测试的启动,@Resource不能进行注入,就会报空指针异常。