Spring 学习笔记1-编写安装程序

本文介绍了一个用于SSH项目的Installer类,该类通过Spring框架实现数据库的初始化。文章详细展示了如何使用@Component和@Resource注解来整合角色、用户及权限服务,并通过main方法启动程序完成数据库初始化流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在编程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不能进行注入,就会报空指针异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值