spring容器对于Bean的创建和对象属性的依赖注入提供了注解的支持,让我们在开发中能够更加便捷的实现对象的创建和对象属性的依赖注入。
一,对于Bean的创建spring容器提供了以下四个注解的支持:
1、@Component
2、@Repository dao层实现类的注解
3、@Service service层实现类的注解
4、@Controller controller层实现类的注解
以上四个注解在普通使用中是等效的,但在web项目中为了区分三层架构中不同层之间Bean的创建,为了避免注解使用的混乱,使用后三个注解进行区分。
二,对于Bean属性的依赖注入分为两类,一类是对于属性是String类型或者基本数据类型Spring容器提供了@Value这个注解,另一类是对于属性是对象的提供了@Autowired和@Resource这两个注解。
其中,@Autowired这个注解是spring框架自带的注解,而@Resource(javax.annotation.Resource)这个注解是java扩展包中注解规范的一种,而spring对这一注解提供了支持。
下面我们通过实验来说明注解对于bean创建和bean属性依赖注入的实现。
首先要在配置文件中配置注解扫描的驱动。
<context:annotation-config/>
<context:component-scan base-package="com.opensource"/>
这里提一句,如果配置了注解扫描包的范围,也就是第二行,那么<context:annotation-config/>可以不用配置,因为配置扫描包的范围后,注解的驱动也就有了。
实验一,bean的创建,因为spring容器对于bean创建的四个注解是等效,这里我们使用@Component这个注解
Student类:
@Component public class Student { public Student(){ System.out.println("spring容器调用Student类的无参构造器"); }
测试类:
public class MyTest { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-bean.xml"); } }
实验结果:

实验二:bean属性为String类型及基本数据类型的的依赖注入
student类:
@Component(value = "student") public class Student { @Value("张三") private String name; @Value("23") private int age; public String getName() { return name; } public int getAge() { return age; } }
在这里 @Component(value = "student") value指定的是bean的id,另外对于注解方式实现的依赖注入,bean的属性无需再提供setter方法。
测试类:
public class MyTest { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-bean.xml"); Student student = (Student)ac.getBean("student"); System.out.println(student.getName()); System.out.println(student.getAge()); } }
实验结果:
原文:http://www.cnblogs.com/cdf-opensource-007/p/6441296.html