Spring 第三讲:IOC操作Bean管理(基于 xml 方式,FactoryBean、Bean 的作用域、Bean 的生命周期、xml 自动装配、基于注解方式)

一、IOC 操作 Bean 管理(基于 xml 方式)

1、什么是 Bean 管理

  • Spring 创建对象
  • Spring 注入属性

2、Bean 管理操作的两种方式

  • 基于 xml 配置文件方式实现。
  • 基于注解方式实现。

3、IOC 操作 Bean 管理(基于 xml 方式)

3.1 基于 xml 方式创建对象

    <!-- 配置User对象创建 -->
    <bean id="User" class="com.spring5.User"></bean>

(1)在 Spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象创建。
(2)在 bean 标签有很多属性,介绍常用的属性。

属性作用
id起名称 ,根据id 获得配置对象
class创建对象所在全路径
name功能和id一样 ,id不能包含特殊符号,name可以(基本不用,为了满足struts1遗留问题)
scopeBean的作用范围
singleton默认值 单例的
prototype多例的
requestweb项目中spring创建一个bean对象,将对象存到request域中
sessionweb项目中…将对象存到session域中
globalSessionweb项目中,应用在prolet环境,如果没有prolet环境那么globalSession相当于session

(3)创建对象时候,默认执行无参构造方法完成对象创建。

3.2 基于 xml 方式注入属性(Set 注入、有参构造注入,p 注入)

  • DI(IOC的实现):依赖注入,就是注入属性。

(1)第一种注入方式:使用set方法进行注入

① 创建类,定义属性和对应的set方法

public class Book {
    //创建属性
    private String bname;
    private String bauthor;
   //set方式注入
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }
    //测试输出书名作者
   public void testOutPut() {
        System.out.println(bname);
        System.out.println(bauthor);
    }
}

② 在 spring 配置文件配置对象创建,配置属性注入(property 标签,k-v 的形式)

     <!-- Set方法注入 -->
    <bean id="book" class="com.spring5.Book">
        <!-- 使用property完成属性注入 name:类里面属性名称 value:向属性注入值-->
        <property name="bname" value="三国演义"></property>
        <property name="bauthor" value="罗贯中"></property>
    </bean>

③ 编写测试类

    @Test
    public void testBook(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Book book = context.getBean("book",Book.class);
        System.out.println(book);
        book.testOutPut();
    }

④ 结果
在这里插入图片描述

(2)第二种注入方式:有参构造进行注入

① 创建类,定义属性,创建属性对应有参数构造方法

public class Orders {

    private String oname;
    private String address;
    
    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }
   
    public void ordersTest(){
        System.out.println(oname);
        System.out.println(address);
    }
}

②在 spring 配置文件配置对象创建,配置属性注入(constructor-arg 标签,k-v 的形式)
可以使用 index ,即索引到第几个参数。

 <!-- 有参构造注入 -->
    <bean id="orders" class="com.spring5.Orders">
        <!-- 使用constructor-arg完成属性注入 name:类里面属性名称 value:向属性注入值-->
        <constructor-arg name="oname" value="苹果"></constructor-arg>
        <constructor-arg name="address" value="China"></constructor-arg>
        <!-- <constructor-arg index="0" value="苹果"></constructor-arg> -->
        <!-- <constructor-arg index="1" value="China"></constructor-arg> -->
    </bean>

③ 编写测试类

    @Test
    public void testOrders(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Orders orders = context.getBean("orders",Orders.class);
        System.out.println(orders);
        orders.ordersTest();
    }

④ 结果
在这里插入图片描述
(3)第三种注入方式:p 名称空间注入

① 添加 p 名称空间在配置文件中

	xmlns:p="http://www.springframework.org/schema/p"

② 使用 p:属性 的方式注入属性,可注入多个

	<bean id="book" class="com.spring5.Book" p:bname="三国演义" p:bauthor="罗贯中"></bean>

3.3 基于 xml 方式注入其他类型属性

(1)字面量(null 和 特殊符号)
① null 值

	<!-- null值 -->
    <property name="address"><null></null></property>

② 属性值包含特殊符号(使用CDATA)

	<!-- 属性值包含特殊符号
            1.把<>转义,可以使用 &lt;&gt; 打出尖括号
            2.把特殊符号内容写到CDATA
         -->
    <property name="address">
         <value><![CDATA[<<中国>>]]></value>
    </property>

(2)注入属性 - 外部 bean
① 创建两个类 service 类和 dao 类
② 在 service 调用 dao 里面的方法

public class UserService {

    private UserDao userDao; 
    //set注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add(){
        System.out.println("service add...");
        userDao.update();
    }
}

③ 在 Spring 配置文件中进行配置

    <!-- service和dao的对象创建 -->
    <bean id="userService" class="com.spring5.service.UserService">
        <!-- 注入userDao对象
            name属性值:service类里面属性值
            ref属性值:创建userDao对象的标签id值
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.spring5.dao.UserDaoImpl"></bean>

④ 测试类

    @Test
    public void testAdd(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }

(3)注入属性 - 内部 bean

① 一对多关系:一个部门有多个员工,一个员工属于一个部门,部门是一,员工是多。
② 在实体类之间表示一对多关系

部门类

//部门类
public class Dept {

    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }
}

员工类

//员工类
public class Emp {

    private String ename;
    private String gender;
    //员工属于某一个部门,使用对象形式表示
    private Dept dept;

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }
}

③ 在Spring 配置文件中进行配置

   <!-- 内部bean -->
    <bean id="emp" class="com.spring5.bean.Emp">
        <!-- 先设置两个普通属性 -->
        <property name="ename" value="Jack"></property>
        <property name="gender" value="m"></property>
        <!-- 再设置对象类型属性 -->
        <property name="dept">
            <bean id="dept" class="com.spring5.bean.Dept">
                <property name="dname" value="财务部"></property>
            </bean>
        </property>
    </bean>

④ 编写测试类

    @Test
    public void testBean2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Emp emp = context.getBean("emp", Emp.class);
        System.out.println(emp);
        emp.toString();
    }

(4)注入属性 - 级联赋值

① 第一种方法:
与内部 bean 同类,同方法

    <!-- 级联赋值 -->
    <bean id="emp" class="com.spring5.bean.Emp">
        <!-- 设置两个普通属性 -->
        <property name="ename" value="Jack"></property>
        <property name="gender" value="m"></property>
        <!-- 级联赋值 -->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.spring5.bean.Dept">
        <property name="dname" value="技术部"></property>
    </bean>

② 第二种方法:

    <!-- 级联赋值 -->
    <bean id="emp" class="com.spring5.bean.Emp">
        <!-- 设置两个普通属性 -->
        <property name="ename" value="Jack"></property>
        <property name="gender" value="m"></property>
        <!-- 级联赋值 -->
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="人力资源部"></property>
    </bean>
    <bean id="dept" class="com.spring5.bean.Dept"></bean>

3.4 基于 xml 注入集合属性

(1)注入数组类型属性
(2)注入 List 集合类型属性
(3)注入 Map 集合类型属性
(4)注入 Set 集合类型属性
(5)在集合里设置对象类型值

① 创建类,定义数组、list、map、set类型属性,生成对应 set 方法

public class Stu {
    //1.数组类型属性
    private String[] array;
    //2.List集合类型属性
    private List<String> list;
    //3.Map集合类型属性
    private Map<String,String> maps;
    //4.Set集合类型属性
    private Set<String> sets;

    //5.学生所学多门课程
    private List<Course> courseList;

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    public void setArray(String[] course) {
        this.array = course;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public void test(){
        System.out.println(Arrays.toString(array));
        System.out.println(list);
        System.out.println(maps);
        System.out.println(sets);
        System.out.println(courseList);
    }
}

② 在Spring 配置文件中进行配置

    <!-- 集合类型属性注入 -->
    <bean id="stu" class="com.spring5.Stu">
        <!-- 数组类型属性注入 -->
        <property name="array" >
            <array>
                <value>江苏</value>
                <value>吉林</value>
            </array>
        </property>
        <!-- list类型属性注入 -->
        <property name="list">
            <list>
                <value>南京</value>
                <value>长春</value>
            </list>
        </property>
        <!-- map类型属性注入 -->
        <property name="maps">
            <map>
                <entry key="江苏" value="南京"></entry>
                <entry key="吉林" value="长春"></entry>
            </map>
        </property>
        <!-- set类型属性注入 -->
        <property name="sets">
            <set>
                <value>南京</value>
                <value>长春</value>
            </set>
        </property>
        <!-- 注入list结合类型,值为对象 -->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
    </bean>

    <!-- 创建多个course对象 -->
    <bean id="course1" class="com.spring5.Course">
        <property name="cname" value="Spring"></property>
    </bean>
    <bean id="course2" class="com.spring5.Course">
        <property name="cname" value="Mybatis"></property>
    </bean>

③ 测试类

    @org.junit.Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Stu stu = context.getBean("stu",Stu.class);
        stu.test();
    }

(6)把集合注入部分提取出来(作为公共部分)

① 在 Spring 配置文件中引入名称空间 util
加入:

       xmlns:util="http://www.springframework.org/schema/util"

修改:

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

② 使用 util 标签去完成 list 集合注入提取

   <!-- 提取list集合类型属性注入 -->
   <util:list id="bookList">
       <value>三国演义</value>
       <value>西游记</value>
   </util:list>

    <!-- 提取list集合类型属性注入使用 -->
    <bean id="book" class="com.spring5.Book">
        <property name="list" ref="bookList"></property>
    </bean>

③ 测试类

    @org.junit.Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book",Book.class);
        book.test();
    }

二、IOC 操作 Bean 管理(FactoryBean)

1、Spring 有两种类型 bean

  • 普通 bean:在配置文件中定义 bean 类型就是返回的类型。
  • 工厂 bean(FactoryBean):在配置文件定义 bean 类型可以和返回类型不一样。

步骤:
(1) 创建类,让这个类作为工厂bean,实现接口 FactoryBean。
(2) 实现接口里面的方法没在实现的方法中定义返回的 bean 类型。

public class MyBean implements FactoryBean<Course> {

    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

(3)配置文件

    <bean id="myBean" class="com.spring5.factorybean.MyBean"></bean>

(4)测试类

@org.junit.Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }

三、IOC 操作 Bean 管理(Bean 的作用域)

1、在 Spring 里面,可以设置创建 bean 实例是单实例还是多实例。

2、在 Spring 里面,默认情况下,bean 是单实例对象。

(1)测试类

    @org.junit.Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = context.getBean("book",Book.class);
        Book book2 = context.getBean("book",Book.class);
        System.out.println(book1);
        System.out.println(book2);
    }

(2)结果

com.spring5.Book@491cc5c9
com.spring5.Book@491cc5c9

(3)如果为 prototype 的情况下

com.spring5.Book@74ad1f1f
com.spring5.Book@6a1aab78

3、如何设置单、多实例

(1)在 Spring 配置文件 bean 标签中有属性 scope 用于设置单实例还是多实例。
(2)scope 属性值

scope 属性值作用
singleton单实例,默认值
prototype多实例
request放在 request 域里
session放在 session 域里

(3)singleton 和 prototype 区别
① singleton 表示单实例,prototype 表示多实例。
② 设置 scope 值为 singleton 时候,加载 spring 配置文件时候就会创建单实例对象。

        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml"); //singleton这里创建
        Book book1 = context.getBean("book",Book.class);

③ 设置 scope 值为 prototype 时候,不是在加载 spring 配置文件时候创建对象,在调用 getBean方法时候创建多实例对象。

        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = context.getBean("book",Book.class); //prototype这里创建

四、IOC 操作 Bean 管理(Bean 的生命周期)

1、生命周期

(1)从对象创建到对象销毁的过程

2、bean 生命周期(bean 生命周期 5 步)

(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)调用 bean 的初始化的方法(需要进行配置)
(4)bean 可以使用了(对象获取到了)
(5)当容器关闭的时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

3、演示 bean 生命周期

(1)Orders 类

public class Orders {

    //无参数构造
    public Orders() {
        System.out.println("1.执行无参构造函数创建bean实例");
    }

    private String oname;

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("2.调用set方法设置值");
    }

    //创建执行的初始化的方法
    public void initMethod(){
        System.out.println("3.执行初始化的方法");
    }

    //创建销毁的方法
    public void destroyMethod(){
        System.out.println("5.执行销毁的方法");
    }
}

(2)xml 配置文件

bean 标签作用
init-method初始化方法,调用类里自己写的
destroy-method销毁方法,调用类里自己写的
    <bean id="orders" class="com.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>

(3)测试类

    @org.junit.Test
    public void test4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("4.获取创建bean实例对象");
        //手动销毁bean实例
        ((ClassPathXmlApplicationContext)context).close();
    }

(4)结果

1.执行无参构造函数创建bean实例
2.调用set方法设置值
3.执行初始化的方法
4.获取创建bean实例对象
5.执行销毁的方法

4、bean 的后置处理器(bean 的生命周期完整 7 步)

(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)【新增 】把bean实例传递 bean 后置处理器的 postProcessBeforeInitialization 方法。
(4)调用 bean 的初始化的方法(需要进行配置)
(5)【新增 】把bean实例传递 bean 后置处理器的 postProcessAfterInitialization 方法。
(6)bean 可以使用了(对象获取到了)
(7)当容器关闭的时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

5、演示添加后置处理器

(1)后置处理器

public class MyBeanPost implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("在我们初始化之前执行的方法");
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("在我们初始化之后执行的方法");
        return o;
    }
}

(2)配置文件

    <bean id="orders" class="com.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>

    <!-- 配置后置处理器,为该xml文件下所有bean加上后置处理器 -->
    <bean id="myBeanPost" class="com.spring5.bean.MyBeanPost"></bean>

(3)测试类

    @org.junit.Test
    public void test4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("4.获取创建bean实例对象");
        //手动销毁bean实例
        ((ClassPathXmlApplicationContext)context).close();
    }

(4)结果

1.执行无参构造函数创建bean实例
2.调用set方法设置值
在我们初始化之前执行的方法
3.执行初始化的方法
在我们初始化之后执行的方法
4.获取创建bean实例对象
5.执行销毁的方法

五、IOC 操作 Bean 管理(xml 自动装配)

1、什么是自动装配

根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入。

2、演示自动装配

注入值bean的id值和类属性名称一样

(1)根据属性名称自动注入

     <!-- 实现自动装配
         bean标签属性值autowire,配置自动装配
         autowire属性常用两个值:
         1.byName根据属性名注入,注入值bean的id值和类属性名称一样
         2.byType根据属性类型注入
     -->
    <bean id="emp" class="com.spring5.autowire.Emp" autowire="byName"></bean>

    <bean id="dept" class="com.spring5.autowire.Dept"></bean>

(2)根据属性类型自动注入

         <!-- 实现自动装配
             bean标签属性值autowire,配置自动装配
             autowire属性常用两个值:
             1.byName根据属性名注入,注入值bean的id值和类属性名称一样
             2.byType根据属性类型注入
         -->
    <bean id="emp" class="com.spring5.autowire.Emp" autowire="byType"></bean>

    <bean id="dept" class="com.spring5.autowire.Dept"></bean>

六、IOC 操作 Bean 管理(外部属性文件)

1、直接配置数据库信息

(1)配置德鲁伊连接池
① pom 文件

    <!-- 5.Druid连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>

② 配置文件
serverTimezone=UTC 防止时区问题

       <!-- 配置Druid连接池 -->
       <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
              <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
              <property name="url" value="jdbc:mysql://localhost:3306/Springsgg?serverTimezone=UTC"></property>
              <property name="username" value="root"></property>
              <property name="password" value="root"></property>
       </bean>

2、引入外部属性文件配置数据库连接池

(1)引入德鲁伊连接池依赖
① 创建外部属性文件 ( jdbc.properties)

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/Springsgg
prop.userName=root
prop.passWord=root

② 把外部 properties 属性文件引入到 spring 配置文件中
③ 引入 context 名称空间
加入:

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/util http://www.springframework.org/schema/util/spring-util.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

④ 在 spring 配置文件使用标签引入外部属性 ( jdbc.properties) 文件

    <!-- 引入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.passWord}"></property>
    </bean>

七、IOC操作Bean管理(基于注解方式)

1、什么是注解

(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)
(2)使用注解,注解作用在类上面,方法上面,属性上面
(3)使用注解目的:简化 xml 配置

2、Spring 针对 Bean 管理中创建对象提供的注解

(1)@Component
(2)@Service
(3)@Controller
(4)@Repository

ps:上面四个注解功能是一样的,都可以用来创建 bean 实例

3、基于注解方式实现对象创建

(1)引入依赖

    <!--spring AOP的包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>

(2)开启组件扫描(找到注解)

如果扫描多个包:

方法一:多个包使用逗号隔开

       <!-- 开启组件扫描-->
       <context:component-scan base-package="com.spring5.dao,com.spring5.service"></context:component-scan>

方法一:多个包扫描包上层目录

       <!-- 开启组件扫描-->
       <context:component-scan base-package="com.spring5"></context:component-213scan>

(3)创建类,在类上面添加创建对象注解

//在注解里value属性值可不写
//默认值是类名称,首字母会自动小写
//UserService --- userService
@Component(value = "userService") //<bean id="userService" class="..."/>
public class UserService {

    public void add(){
        System.out.println("service add...");
    }

}

(4)测试类

    @org.junit.Test
    public void testService(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService",UserService.class);
        System.out.println(userService);
        userService.add();
    }

(5)注意

  • 在注解里value属性值可不写,默认值是类名称,首字母会自动小写。
  • 四个注解是等效的,可以将Component替换成Service或者其他注解。

4、开启组件扫描细节配置

(1)context:include-filter

       <!-- 示例1
              use-default-filters="false"表示不使用默认filter,自己配置 表示不使用默认filter  
              context:include-filter,设置扫描哪些内容
              (expression="org.springframework.stereotype.Controller" 表示只扫描Controller)
       -->
       <context:component-scan base-package="com.spring5" use-default-filters="false">
              <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
       </context:component-scan>

(2)context:exclude-filter

       <!-- 示例2
             use-default-filters="false"表示不使用默认filter,自己配置 表示不使用默认filter
             context:exclude-filter,设置不扫描哪些内容
             (expression="org.springframework.stereotype.Controller" 表示不扫描Controller)
       -->
       <context:component-scan base-package="com.spring5" use-default-filters="false">
              <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
       </context:component-scan>

5、基于注解方式实现属性注入

5.1 对象类型属性

(1)@Autowired:根据属性类型进行自动装配。

  1. 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解。
@Repository(value = "a")
public class UserDaoImpl implements UserDao{

    @Override
    public void add() {
        System.out.println("dao add...");
    }
}
  1. 在 service 内注入 dao 对象,在 service 类添加 dao 类属性,在属性上面使用注解
@Service
public class UserService {
    //添加dao类型属性
    //不需要添加set方法
    //添加注入属性注解
    @Autowired
    private UserDao userDao;

    public void add(){
        System.out.println("service add...");
        userDao.add();
    }
}

(2)@Qualifier:根据属性名称进行注入。

这个注解的使用需要搭配 @Autowired 一起使用

    @Autowired
    @Qualifier(value = "a") //根据value为a的userDaoImpl注入
    private UserDao userDao;

(3)@Resource:可以根据类型注入,可以根据名称注入。

  1. 根据类型注入
    @Resource
    private UserDao userDao;
  1. 根据名称 name 注入
    @Resource(name = "a")
    private UserDao userDao;
  1. 其实相当于@Autowired+@Qualifier,但是@Resource是 javax 提供的扩展属性,不是 Spring 自带属性。

5.2 普通类型属性

(1)@Value:注入普通类型属性。

@Service(value = "userService") 
public class UserService {

    @Value(value="Hello World")
    private String name;

    public void add(){
        System.out.println(name);
    }

}

6、完全注解开发

(1)创建配置类,替代 xml 配置文件

@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.spring5"}) //扫描注解
public class SpringConfig {

}

(2)编写测试类

    @org.junit.Test
    public void testService(){
        //加载配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService",UserService.class);
        System.out.println(userService);
        userService.add();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值