1. 创建 web 项目
2. 引入 jar 包
3. 日志文件
4. 创建实体类
Person
Car
5. 创建 applicationContext.xml
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- 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
- https://www.springframework.org/schema/context/spring-context.xsd">
- </beans>
6. 配置注解扫描
指定要扫描的包
<context:component-scan base-package="com.spring.pojo"></context:component-scan>
7. 在类中使用注解
- @Component("person")
- @Repository("person")
- @Service("person")
- @Controller("person")
- //<bean name="person" class="com.Spring.pojo.Person"></bean> 相同
8. 其他类级别的注释
- @Component("person") // 适用于所有组件
- @Repository("person") // 适用于持久层
- @Service("person") // 适用于 service
- @Controller("person") // 适用于 controller
9. 指定对象的 scope 的属性
- @Component("person")
- @Scope(scopeName="singleton")
10.set 方式注入 value 值
1 - 在私有的成员变量中注入
- @Value("helen") [email protected](value="helen")
- @Value("helen")
- private String name;
- @Value("18")
- private Integer age;
2 - 在 set 方法中注入
- @Value("tom")
- public void setName(String name) {
- this.name = name;
- }
11. 自动装配
@Autowired 进行自动装配, 按照对象类型进行自动装配
- @Component("car")
- public class Car {
- @Value("小黄车")
- private String name;
- @Value("蓝色")
- private String color;
- public class Person {
- @Value("helen")
- private String name;
- @Value("18")
- private Integer age;
- @Autowired
- private Car car;
自动装配存在的问题: 如果一个类型有多个对象, 那么可以采取以下的方式
方法一:
使用指定 @Qualifier 指定具体的对象
- @Autowired
- @Qualifier("car2")
- private Car car;
方式二:
使用 @Resource 指定具体的对象
- @Resource(name="car1")
- private Car car;
12. 初始化方法和销毁方法
- @PostConstruct // 初始化
- public void init() {
- System.out.println("Person 被初始化了...");
- }
- @PreDestroy // 销毁
- public void destroy() {
- System.out.println("Person 被摧毁了...");
- }
来源: http://www.bubuko.com/infodetail-3367891.html