那些年、一起追过的Spring--(4)----注解

来源:互联网 发布:安居客网络门店系统 编辑:程序博客网 时间:2024/05/16 09:30

注解的目的:

Spring的注解是在Spring2.5的版本中引入的,目的简化XML配置。


@Component注解:
作用:将java类注入到Spring框架中。相当于我们前面配置的

<bean id="person" class="entity.Person"></bean>

当使用了Spring注解之后,需要在配置文件中添加

<context:component-scan base-package=""></context:component-scan>

来扫描添加了注解的类,这样声明注解的类才会起作用。


除了@Component注解之外,Spring容器还提供了三个功能和@Component相同的注解

  1. @Repository:用于对Dao实现类注解
  2. @Service:用于对Service实现类注解
  3. @Controller:用于对Controller实现类注解

Autowired注解:
Spring 2.5引入了@Autowired注解。
作用:可以对类成员变量,方法,构造函数进行标注,完成自动装配的工作;而且还可以实现Bean之间的依赖关系。


代码案例:

package com.spring;import org.springframework.stereotype.Component;@Componentpublic class TeacherAnnotation {    public void print() {        System.out.println("hello");    }}
package com.spring;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class StudentAnnotation {    @Autowired    private TeacherAnnotation teacher;    public void helloTeacher(){        teacher.print();    }}
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd">    <context:component-scan base-package="com.spring"></context:component-scan></beans>
package com.spring.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.StudentAnnotation;public class test01 {    public static void main(String[] args) {        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");        StudentAnnotation stu=(StudentAnnotation)context.getBean("studentAnnotation");        stu.helloTeacher();    }}

输出结果:

hello

@Qualifier注解:
@Qualifier –>指定注入Bean的名称

阅读全文
0 0