Spring Annotation(二)
在使用注释配置之前,先来回顾一下传统上是如何配置 Bean 并完成 Bean 之间依赖关系的建立。下面是 3 个类,它们分别是 Office、Car 和 Boss,这 3 个类需要在 Spring 容器中配置为 Bean:
Office 仅有一个属性:
清单 1. Office.java
package com.baobaotao;
public class Office {
private String officeNo =”001”;
//省略 get/setter
@Override
public String toString() {
return "officeNo:" + officeNo;
}
}
|
Car 拥有两个属性:
清单 2. Car.java
package com.baobaotao;
public class Car {
private String brand;
private double price;
// 省略 get/setter
@Override
public String toString() {
return "brand:" + brand + "," + "price:" + price;
}
}
|
Boss 拥有 Office 和 Car 类型的两个属性:
清单 3. Boss.java
package com.baobaotao;
public class Boss {
private Car car;
private Office office;
// 省略 get/setter
@Override
public String toString() {
return "car:" + car + "\n" + "office:" + office;
}
}
|
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:
清单 4. beans.xml 将以上三个类配置成 Bean
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="boss" class="com.baobaotao.Boss">
<property name="car" ref="car"/>
<property name="office" ref="office" />
</bean>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="002"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
|
当我们运行以下代码时,控制台将正确打出 boss 的信息:
清单 5. 测试类:AnnoIoCTest.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnoIoCTest {
public static void main(String[] args) {
String[] locations = {"beans.xml"};
ApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
}
}
|
这说明 Spring 容器已经正确完成了 Bean 创建和装配的工作。
分享到:
相关推荐
Spring annotation 样例
Spring Annotation
spring annotation注解 使用Spring注解来注入属性
spring的Annotation注解.
NULL 博文链接:https://cyhcheng.iteye.com/blog/390551
Spring的Annotation配置相关讲义
详解 Spring 3.0 基于 Annotation 的依赖注入实现。。详解 Spring 3.0 基于 Annotation 的依赖注入实现。。
花了些时间做了一个实验,彻底弄懂了spring Annotation注入的方式。凡带有@Component,@Controller,@Service,@Repository 标志的等于告诉Spring这类将自动产生对象,而@Resource则等于XML配置中的ref,告诉spring此处...
Spring_Annotation_AOP
关于Spring annotation的详细介绍,包括 @Component,@Autowired 等,感觉还不错。
Spring+mybatis annotation形式 进行增删查改,使用maven容器,配置完整,自己运行多次无问题
SpringMVC Spring MyBatis 框架整合 Annotation Maven Project
NULL 博文链接:https://dolphin-ygj.iteye.com/blog/548314
Spring IOC Annotation 注入 学习实例
spring annotation 从入门到精通
spring annotation 注解 maven 配套的源码
spring annotation example source code java maven
Spring注解开发代码+脑图+源码分析+spingmvc源码分析
spring使用annotation整合dwr笔记 spring使用annotation整合dwr笔记 spring使用annotation整合dwr笔记