超详细讲解Spring框架的Bean管理 和IOC纯注解方式

一.什么是Bean个管理

bean管理指的是如下的两个操作。

1.创建对象 2.注入属性

二.Bean管理操作的两种方式

1.基于xml配置文件的方式实现 2.基于注解方式实现

首先讲解一下基于xml配置文件的方式实现Bean管理和注入属性

1.基于xml方式创建对象

①:这个就是我们上边配置过

②:创建对象的时候,默认是执行无参构造方法完成对象

再次运行

2.基于xml方式注入属性

  • 依赖注入的概述

IOC和DI的概念

IOC:Inverse of Control,控制反转,将对象的创建权反转给Spring!!

DI:Dependency Injection,依赖注入,就是注入属性

  • 属性的set方法注入值

编写属性,提供该属性对应的set方法,编写配置文件完成属性值的注入

public class User {
    // 编写成员属性,一定需要提供该属性的set方法
    //IOC容器底层就通过属性的set方法方式注入值
    private int age;
    private String name;
    private Demo demo;

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDemo(Demo demo) {
        this.demo = demo;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", demo=" + demo +
                '}';
    }
}

xml配置文件:

<!‐‐DI:依赖注入‐‐>
<bean id="user" class="com.qcby.service.User" >
    <!--使用property完成属性注入
        name:类里面属性名称
        value:向属性注入值
        ref:对象映射-->
    <property name="age" value="18"></property>
    <property name="name" value="张三"></property>
    <property name="demo" ref="demo"></property>
</bean>

<bean id="demo" class="com.qcby.service.Demo" />

测试类:

@Test
public void run1(){
    //创建spring工厂,加载配置文件
    ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    //获取bean对象
    User user = ac.getBean("user", User.class);

    System.out.println(user.toString());

}
  • 属性构造方法方式注入值

对于类成员变量,构造函数注入。

    public User(int age,String name,Demo demo){
        this.age=age;
        this.demo=demo;
        this.name=name;
    }
    利用构造器注入
    <bean id="user" class="com.qcby.User">
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="name" value="lisi"></constructor-arg>
        <constructor-arg name="demo" ref="demo"></constructor-arg>
    </bean>
    @Test
    public void run1(){
        AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
        User user=(User)ac.getBean("user");
        //user.hello();
        System.out.println(user.toString());
    }
  • 数组,集合(List,Set,Map)等的注入
public class CollectionBean {

    private String [] strs;
    private List<String> list;
    private Map<String,String> map;

    public void setStrs(String[] strs) {
        this.strs = strs;
    }

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

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "CollectionBean{" +
                "strs=" + Arrays.toString(strs) +
                ", list=" + list +
                ", map=" + map +
                '}';
    }
}
<!‐‐给集合属性注入值‐‐>
<bean id="collectionBean" class="com.qcby.service.CollectionBean">
    <property name="strs">
        <array>
            <value>美美</value>
            <value>小凤</value>
        </array>
    </property>
    <property name="list">
        <list>
            <value>熊大</value>
            <value>熊二</value>
        </list>
    </property>
    <property name="map">
        <map>
            <entry key="aaa" value="老王"/>
            <entry key="bbb" value="小王"/>
        </map>
    </property>
</bean>
public class CollectionTest {
    @Test
    public void run(){
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean collectionBean=(CollectionBean) ac.getBean("collection");
        System.out.println(collectionBean.toString());
    }
}

下面再来说说第二种基于注解的方式实现Bean管理和注入属性

1.什么是注解

①:注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)

②:使用注解,注解作用在类上面,方法上面,属性上边

③:使用注解的目的:简化XML配置

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

@Component 普通的类

@Controller 表现层

@Service 业务层

@Repository 持久层

*上边四个功能一样,都可以用来创建bean实例

3.用注解的方式创建对象

①:编写接口和实现类

package com.qcby.testanno;

public interface UserService {
    public void hello();
}

②:在需要管理的类上添加@Component注解

package com.qcby.testanno;

import org.springframework.stereotype.Component;

/* <bean id="us" class="UserServiceImpl"/> */
/**
 * 组件,作用:把当前类使用IOC容器进行管理,如果没有指定名称,默认使用类名,首字母是小写。
 * userServiceImpl。或者自己指定名称
 **/
@Controller(value="us")
public class UserServiceImpl implements UserService {
    public void hello() {
        System.out.println("使用注解,方便吧!");
    }
}

③:编写配置文件,重点是开启注解扫描。

<?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: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">
   
    <!--开启注解扫描 com.qcby所有的包中的所有的类-->
    <context:component-scan base-package="com.qcby"/>
</beans>

编写测试方法

package com.qcby.test;

import com.qcby.testanno.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo2 {
    @Test
    public void run1(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContextanno.xml");
        UserService us = (UserService) ac.getBean("us");
        us.hello();
    }
}

4.用注解的方实现属性注入

@Value 用于注入普通类型(String,int,double等类型)

@Autowired 默认按类型进行自动装配(引用类型)

@Qualifier 不能单独使用必须和@Autowired一起使用,强制使用名称注入

@Resource Java提供的注解,也被支持。使用name属性,按名称注入

具体的代码如下

注意Autowired注解时要将构造器和扫描配置注释掉

package com.qcby;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/*
@Autowired 用于引用类型 要删掉构造器
    public User(int age,String name,Demo demo){
        this.age=age;
        this.demo=demo;
        this.name=name;
    }
 */
@Component
//@value()用于注入普通类型:作用在(String,int,double等类型)
public class User {
    @Value("18")
    private  int age;
    @Value("张三")
    private String name;
@Autowired

    private Demo demo;
//    public User(int age,String name,Demo demo){
//        this.age=age;
//        this.demo=demo;
//        this.name=name;
//    }
 //扫描器里也给注释掉

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Demo getDemo() {
        return demo;
    }

    public void setDemo(Demo demo) {
        this.demo = demo;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", demo=" + demo +
                '}';
    }
    public void hello() {
        System.out.println("hello world");
    }
}
<?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: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">

   <!-- <bean id="demo" class="com.qcby.Demo">

    </bean> -->

重中之重:IOC纯注解的方式

纯注解的方式是微服务架构开发的主要方式,所以也是非常的重要。纯注解的目的是替换掉所有的配置文件。但是需要编写配置类。

常用的注解总结

@Configuration 声明是配置类

@ComponentScan 扫描具体包结构的

编写实体类

package com.qcby;

import org.springframework.stereotype.Component;

@Component
public class Demo {
    public void hello() {
        System.out.println("hello world");
    }

}

创建包config,编写配置类SpringConfig,替换掉applicationContext.xml配置文件

package com.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//声明配置类
@Configuration
@ComponentScan(value = "com.qcby")
public class SpringConfig {
}

测试类

   @Test
    public void run1(){
        //1.加载配置文件
        ClassPathXmlApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.获取JavaBean对象 告知对象类型--强制类型转换
        Demo demo=(Demo)ac.getBean("demo");
        //3。方法调用
        demo.hello();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值