注解配置spring
一、步骤
1、导包:4+2+spring-aop
2、为主配置文件引入新的命名空间(约束)
3、开启使用注解代理配置文件
<!-- 指定扫描cn.shop.bean报下的所有类中的注解. 注意:扫描包时.会扫描指定报下的所有子孙包 --> <context:component-scan base-package="cn.shop.bean"></context:component-scan>4、在类中使用注解完成配置
二、将对象注册到容器
@Component("user") @Service("user") // service层 @Controller("user") // web层 @Repository("user")// dao层
三、修改对象的作用范围
//指定对象的作用范围 @Scope(scopeName="singleton")
四、值类型注入
通过反射的Field赋值,破坏了封装性:
@Value("tom") private String name;
通过set方法赋值,推荐使用:
@Value("tom") public void setName(String name) { this.name = name; }
五、引用类型注入
//@Autowired //自动装配 //问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象. //@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象 @Resource(name="car")//手动注入,指定注入哪个名称的对象(重点) private Car car;
六、初始化和销毁方法
@PostConstruct //在对象被创建后调用.init-method public void init(){ System.out.println("我是初始化方法!"); } @PreDestroy //在销毁之前调用.destory-method public void destory(){ System.out.println("我是销毁方法!"); }
junit整合测试
一、导包:4+2+aop+test
二、配置注解和测试
//帮我们创建容器 @RunWith(SpringJUnit4ClassRunner.class) //指定创建容器时使用哪个配置文件 @ContextConfiguration("classpath:applicationContext.xml") public class Demo { //将名为user的对象注入到u变量中 @Resource(name="user") private User u; @Test public void fun1(){ System.out.println(u); } }