基本知识点如下:
- 引入注解约束,配置组件扫描
- 类上的注解: @Conponent @Controller @Service @Repository
- 普通属性的注解 @value
- 对象属性的注解 @Resource @Autowired @Qualifier
- Bean生命周期,初始化与销毁: @PostConstruct @PreDestroy
- Bean作用范围:@Scope("prototype") , 默认是singleton
1.创建web项目引入jar包
除了IOC基本的六个包,再引入AOP开发的包
2.引入spring的配置文件
- 创建applicationContext3.xml
- 引入约束:使用注解开发引入context约束
- file:///D:/Hibernate/Spring/spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.htm
<!-- ========================引入spring关于注解开发的context约束======================== -->
<?xml version="1.0" encoding="UTF-8"?>
<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
http://www.springframework.org/schema/context/spring-context.xsd"> </beans>
3.创建接口和实现类以及测试类
package spring.day2.demo1; public interface UserDao {
public void save();
}
package spring.day2.demo1; public class UserDaoImp1 implements UserDao { @Override
public void save() {
System.out.println("userdao的save方法已经执行.......");
} }
package spring.day2.demo1; import org.junit.Test; /*
* IOC注解开发入门
*/
public class SpringDemo1 {
@Test
/*
* 传统方式
*/
public void demo1() {
UserDao userDao = new UserDaoImp1();
userDao.save();
}
}
4.在配置文件中配置IOC的组件扫描,确认哪些包下的类要使用注解
5.添加注解
6.去测试类中添加如下代码测试
@Test
/*
* IOC的注解方式
*/
public void demo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext3.xml");
UserDao bean = (UserDao) applicationContext.getBean("userDao");
bean.save();
}