Spring第二天
来源:互联网 发布:java面向对象封装 编辑:程序博客网 时间:2024/05/26 07:27
注解配置Spring
步骤
1.导包4+2+spring-aop
2.为配置文件引入新的命名空间
3.开启使用注解代理配置文件
<context:component-scan base-package="cn.lxs.bean"></context:component-scan>
4.在类中使用注解完成配置
将对象注册到容器
``` 相当于<bean name="user" class="cn.lxs.bean.User"/> @Component("user") @Service("user")//service层 @Controller("user")//web层 @Repository("user")//dao层 //指定对象的作用范围 @Scope(scopeName="prototype")默认的属性是singleton```①值类型注入``` //通过反射的Field赋值,破坏了封装性@Value("tom")private String name;//通过set方法赋值,推荐使用@Value("tom")public void setName(String name){ this.name=name;}``` ②引用类型注入```@Autowired//自动装配//缺点:如果匹配多个类型一致的对象,将无法选择具体注入哪个对象@Qualifier("car2")//使用@Qualifier注释告诉Spring容器自动装配哪个名称的对象private Car car;`````` @Resource(name="car")//手动注入,指定注入哪个名称的对象 private Car car; ``` ③初始化|销毁方法 ``` @PostConstruct//在对象被创建后调用.init-method public void init(){ System.out.println("我是初始化方法!!!"); } @PreDestory//在销毁之前使用destory-method public void destory(){ System.out.println("我是销毁方法!"); }```安装STS插件,如果安装成功了,在applicationContext.xml上右点open with,再点Spring Config Editor
Spring与junit整合测试
1.导包4+2+aop+test
2.配置注解
如果用原来的方法需要每次在测试的方法里通过ApplicationContext ac=new ClassPathXmlApplicationContext(“applicationContext.xml”);加载配置文件,创建容器。
改进:
//帮我们创建容器@Runwith(SpringJUnit4ClassRunner.class)//指定创建容器时,使用哪个配置文件@ContextConfiguration("classpath:applicationContext.xml");public class Demo{ //将名为user的对象注入到u变量中 @Resource(name="user") private User u;}
阅读全文