一..注解 全注解 整合
注解:注解的概念
注解(Annotation),也叫元数据(MetaData)信息 。一种代码级别的说明。
它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。
它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,
用来对这些元素进行说明,注释
二.使用注解DI的步骤
注解DI的作用:替代xml节点中的所有bean节点
@Component 标识一个类是被spring容器管理的一个bean
@Value 给类的普通属性赋值
@Resource 给类的域属性赋值 JDK提供的注解
@Autowired 给类的域属性赋值 Spring容器提供的 这个注解不能直接给属性赋值 需要用到@Qualifier(value="student")
配置步骤:
1.引入命名空间 context
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
2.在xml节点中写一个包扫描器
<context:component-scan base-package="happy"> 全类名 </context:component-scan>
3.实体类如何使用注解?
@Component("student") public class Student { @Value("张三") private String name; @Value("20") private Integer age; @Resource(name="cars") private Car car; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", car=" + car + '}'; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
4.测试类测试代码:
//注解 @Test public void Test06(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext06.xml"); Student student =(Student) context.getBean("student"); System.out.println(student); }
5.运行结果如下:
三.autowire自动注入配置
autowire有了之后,就不需要res来链接bean节点 属性值有byType byName
<bean id="cars" class="happy.Car"> <property name="color" value="蓝色"></property> <property name="brand" value="布加迪威龙"></property> </bean> <!--自动配置 这里急不需要用ref来引入上边所写的bean节点 设置bean节点的属性为autowire--> <bean id="student" class="happy.Student" autowire="byType"> <property name="name" value="李四"></property> <property name="age" value="20"></property> </bean>