1.准备工作
(1)导入jar包
除了上篇文章使用到的基本jar包外,还得加入aop的jar包,所有jar包如下
所需jar包
(2)配置xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
2.注解实例化Bean
(1)实例化Bean有四个注解
@Component
@Service:业务层
@Controller:WEB层
@Repository:持久层
虽然分了层,但目前这四个注解的功能是一样的。
@Service(value = "user") //相当于bean标签中的id,四种方式功能一样
// @Component(value = "user")
// @Controller(value = "user")
// @Repository(value = "user")
@Scope(value = "singleton")
public class User {
public void print() {
System.out.println("user......");
}
}
@Test
/**
* 使用注解实例化User类
*/
public void testUser() {
// 读取配置文件
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = (User)context.getBean("user");
user.print();
}
bean的作用域配置
Spring中可以使用scope属性来配置bean的作用域:
singleton:单例,在初始化配置文件时生成单例bean对象
prototype:原型的,在初始化配置文件时不生成bean对象,使用时返回不同的bean对象