spring03 使用注解的方式 配置bean和实现依赖的注入及整合Junite测试环境
一,使用注解配置Spring
1.在applicationContext.xml配置文件中配置
<context : component-scan base-package = "cn.itcast.beam."></context>
<!--指定扫描的那个包下的所有的类 -->
<context:component-scan base-package="cn.itcast.beam.User"></context:component-scan>
2.再类中使用注解完成配置
package cn.itcast.beam;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
//本质上都是一样的,但是为了更加符合我们的思维习惯,javaee中三层架构的思想
//对象类型的注入
@Component("user")
@Service("user")
@Controller("user")
@Repository("user")
// 指定对象的作用范围 其中 sington表示单例模式 prototype表示多例模式
@Scope(scopeName = "prototype")
public class User {
// 值类型的注入 通过反射的filed赋值 破坏了封装性
// @Value("tom")
private String name;
@Value("18")
private Integer age;
// 引用类型的注入方式 第一种自动装配 第二种 手动注入 推荐使用手动注入
// 1.自动装配 如果有多个对象 不知道注入哪一个对象
@Autowired
@Qualifier("car2") // 使用这个属性高速spring容器自动装配那个
private Car car;
// 2.手动注入
@Resource(name = "car")
private Car car2;
public String getName() {
return name;
}
// 这个时作用自方法上 使用set方法赋值
@Value("tom")
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
package cn.itcast.beam;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定容器使用那个配置文件
@ContextConfiguration("claspath:applicationContext.xml")
public class demo {
// 将名为user的对象注入到u变量中
@Resource(name="user")
private User u;
@Test
public void fun2(){
System.out.println(u);
}
/*@Test
public void fun1() {
// 创建一个容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 想容器要user对象
User u = (User) ac.getBean("user");
System.out.println(u);
}
*/
}