Spring自动装配

Spring 的自动装配 xml文件配置的方式

   

   

  1.     <?xml version="1.0" encoding="UTF-8"?>
  2.     <beans xmlns="http://www.springframework.org/schema/beans"
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.         xmlns:p="http://www.springframework.org/schema/p"
  5.         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
  6.         default-autowire="byname">  <!--    通过byName全局自动装配 -- >

   

1、通过autowrite="byName": Student的Teacher 属性必须等于 teacher<bean>的Id

   

  1.         1. <bean id="teacher" class="cn.tri.vo.Teacher" p:name="yefan" p:age="18"></bean>
  2.         2. <bean id="stu" class="cn.tri.vo.Student" p:id="6" p:name="liming" p:age="8" autowire="byName">

   

2、通过autowrite="byType": byType类型 会自动寻找一个与Teacher类的bean,但是类型相同的多个bean通过ByType注入会报错

   

3、通过autowrite="Constrcuctor": constrcutor根据构造方法寻找,其他bean的类型是否与该类的构造器参数方法一致

   

   

Spring 的自动装配 通过注解的方式:

@Component("stu") 总注解

   

dao层注解:@Respository

   

service层注解:@Service

   

controller层注解:@Controller

   

使用注解有个前提,必须在application.xml文件中配置

<context:component-scan package="配置有上面注解的包名">

   

   

  1.     @Component("TeacherDaoImpl")    //id="TeacherDaoImpl" 的bean
  2.     public class TeacherDaoImpl implements TeacherDao{
  3.         public void getshow() {
  4.             System.out.println("我是一名中国老师");
  5.         }
  6.     }

   

等同于

<bean id="TeacherDaoImpl" class="cn.tri.dao.impl"></bean>

   

posted @ 2020-10-17 16:41  黑质白章  阅读(119)  评论(0编辑  收藏  举报