【Spring三】使用注解配置bean

来源:互联网 发布:外星文明不存在 知乎 编辑:程序博客网 时间:2024/05/20 04:14
一.注解形式实现DI,给引用属性赋值:@Resource(name="xx")

1、在spring的配置文件中,加入命名空间
        xmlns:context="http://www.springframework.org/schema/context"
        http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
2、在spring的配置文件中,开启注解解析器
       <context:annotation-config></context:annotation-config>

3、把person和student放入到spring容器中
       <bean id="person" class="cn.itheima03.spring.di.annotation.Person"></bean>
       <bean id="student" class="cn.itheima03.spring.di.annotation.Student"></bean>
     
    配置文件:
<?xml version= "1.0" encoding ="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
       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
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
   <bean id="person" class="cn.itheima03.spring.di.annotation.Person" ></bean>
   <bean id="student" class="cn.itheima03.spring.di.annotation.Student" ></bean>
   <!--
           1 引入命名空间
           2、启动注解解析器
    -->
    <context:annotation-config></ context:annotation-config>
</beans>

4、在Person类中的student不需要set和get方法,直接在属性上配置@Resource注解
public class Person {
     private Long pid;
//   @Autowired//按照类型匹配
//   @Qualifier("student")//id匹配
     
     @Resource(name= "student")
     private Student student;
     
     public void show(){
           this.student .show();
     }
}



原理:
     1、当启动spring容器的时候,给spring容器的bean创建对象
     2、当spring容器解析到<context:annotation-config></context:annotation-config>的时候,
         spring容器扫描在spring容器中的bean
     3、查看bean中的属性或者方法上有没有@Resource
            (1)、有
                ①、如果该注解的属性name的值为"",则会按照属性的名称和spring中的ID值进行匹配,如果匹配
                  成功,则赋值,如果匹配不成功,则按照类型进行匹配,如果类型匹配不成功,则报错
                ②、如果该注解的属性name的值不为"",则按照name属性的值和spring中的ID值进行匹配,
                   如果匹配成功,则赋值,匹配不成功,则报错
            (2)、没有

说明:
   基本类型不能用注解赋值 
   注解的效率没有xml文件的高,但是书写比较简单
   @Autowired按照类型进行匹配 
   @Qualifier("studen")按照ID进行匹配
   按照类型匹配比较危险

通过@Resource(name="student")对引用属性进行赋值,等效于在<bean>中配置:
        <property name= "student">
               <ref bean= "student" />
      </property>
只不过通过property标签来给属性设置值时,需要get/set方法,而是用注解则不需要。

二.类的扫描机制:@Component(value="xx")

为了在配置文件中不写<bean>标签,可以在类上使用component注解来解决。步骤:
   1、在spring的配置文件中,引入命名空间
        xmlns:context="http://www.springframework.org/schema/context"
        http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd

   2、添加类的扫描解析器
     <context:component-scan base-package="cn.itheima03.spring.scan"></context:component-scan>        既包含了依赖注入的注解解析器,还包含了类扫描的
   3、在一个类上标注注解
                        @Component
                        public class Person {}
                        等效于
                        <bean id="person" class="..Person">
            配置注解属性:
                        @Component(value="aa")
                        public class Person {}
                        等效于
                        <bean id="aa" class="..Person">
        spring容器会为该bean创建对象,id值为:
                  ①如果该注解没有value属性,则值为类的第一个字母变成小写,其他的不变
                  ②如果有value属性,则用value属性的值作为ID的值

   4、执行@Resource注解的流程

使用的注解越多,在xml文件中写的内容越少,效率越低
更多典型化注解:
     @Controller
     @Service
     @Repository
     其作用和用法与@Component保持一致,用法见下例子二。

注意:
     在一个类中有一个基本类型的属性,如果该类是以注解的形式放入到spring容器中的,基本属性在这里是没有办法赋值的
     利用注解的方式实现继承,不需要使用Parent

演示代码:

配置文件:
<?xml version= "1.0" encoding ="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
       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
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:component-scan base-package="cn.itheima03.spring.scan" ></context:component-scan>
</beans>

例子一.Document:
  
public interface Document {
     public void read();
     public void write();
}
=========================
@Component("excelDocument" )
public class ExcelDocument implements Document{
     public void read() {
          System. out.println("read excel" );
     }
     public void write() {
          System. out.println("write excel" );
     }
}

======================
@Component("pdfDocument" )
public class PDFDocument implements Document{
     public void read() {
          System. out.println("read pdf" );
     }
     public void write() {
          System. out.println("write pdf" );
     }
}

=====================
@Component ("documentManager" )
public class DocumentManager {
      @Resource(name= "pdfDocument" )
      private Document document;

      public void read(){
           this .document .read();
     }
      public void write(){
           this .document .write();
     }
}
=======================
public class DocumentTest {
     @Test
     public void test(){
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
          DocumentManager documentManager = (DocumentManager) context.getBean("documentManager" );
          documentManager.read();
          documentManager.write();
     }
}


 例子二.MVC:
@Repository("personDao" )
public class PersonDaoImpl implements PersonDao{

     @Override
     public void savePerson() {
          System. out.println("save person" );
     }
}
============================
@Service("personService" )
public class PersonServiceImpl implements PersonService{
     @Resource(name= "personDao")
     private PersonDao personDao;
     
     public void savePerson() {
           this.personDao .savePerson();
     }
}
============================
@Controller("personAction" )
public class PersonActionImpl implements PersonAction{
     
     @Resource(name= "personService")
     private PersonService personService;

     public void savePerson() {
           this.personService .savePerson();
     }
}
============================
public class MVCTest {
     @Test
     public void testMVC(){
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
          PersonAction personAction = (PersonAction)context.getBean("personAction" );
          personAction.savePerson();
     }
}




0 0
原创粉丝点击