================================= Spring IoC注解配置之Component注解 ================================= 1 为实体类添加Component(组件)注解 对象ID | v @Component(value = "student") public class Student { ... } Spring会在指定范围(包)中扫描所有带有Component注解的类,创建并管理该类的实例。 2 测试 在cn.tedu.annotationioc.test包中创建SpringTest类: public class SpringTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student student = context.getBean("student", Student.class); System.out.println(student); } } 运行测试: Student{number='null', name='null', gender='null', age=0, enrollment=null} 例程:AnnotationIoC 更简单的写法: @Component("student") // value关键字可以省略不写 public class Student { ... } @Component // 默认对象ID为类名首字母改小写 public class Student { ... } 3 Component注解 Component注解用于声明此类被Spring容器管理,相当于XML文件中的bean标签。 Component注解的value属性用于指定Bean对象的ID,相当于bean标签的id属性。 Component注解的value属性可以省略,Bean对象的默认ID为类名首字母改小写。 Service、Controller和Repository注解的功能与Component等价,仅语义不同: - Service:业务处理类,如Service接口的实现类 - Controller:控制器类,如Servlet类 - Repository:持久化类,如DAO接口(其实现类不一定有,如使用MyBatis) - Component:其它类 4 属性初值 通过Component注解配置对象,属性的初值可以直接在类中指定: @Component(value = "student") public class Student { private String number = "1001"; private String name = "张飞"; private String gender = "男"; private int age = 20; private Date enrollment = new Date(); ... } 例程:AnnotationIoC