Spring IOC详细配置与使用实例

IOC理论推导

  • 新建一个maven项目,导入以下依赖
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.3.12</version>
</dependency>
  • UserDao接口
public interface UserDao {
    void getUser();
}
  • UserDaoImpl类
public class UserDaoImpl implements UserDao{
    public void getUser() {
        System.out.println("获取用户");
    }
}
  • UserService接口
public interface UserService {
    void getUser();
}
  • UserServiceImpl类
public class UserServiceImpl implements UserService{
    private UserDao userDao = new UserDaoImpl();

    public void getUser() {
        userDao.getUser();
    }
}
  • UserTest测试类
public class UserTest {
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }
}
  • 测试结果
    在这里插入图片描述
  • 这时我们增加需求,添加一个UserMysqlDaoImpl实现UserDao接口
public class UserMysqlDaoImpl implements UserDao{
    public void getUser() {
        System.out.println("Mysql获取用户");
    }
}
  • 如果用户需要使用这个类代替之前得UserDaoImpl,就需要在UserServiceImpl中修改
public class UserServiceImpl implements UserService{
	//修改new的对象,改为UserMysqlDaoImpl
    private UserDao userDao = new UserMysqlDaoImpl();

    public void getUser() {
        userDao.getUser();
    }
}
  • 测试结果
    在这里插入图片描述
  • 如果每增加一个需求,就要在UserServiceImpl中修改,此时控制用哪个DaoImpl就由程序员来完成,很繁琐,如果我们想让用户自己来操作呢?
    可以在UserServiceImpl中使用set注入
public class UserServiceImpl implements UserService{
    private UserDao userDao;

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

    public void getUser() {
        userDao.getUser();
    }
}
  • 这样如果我们想使用哪个DaoImpl,只需要在UserTest中调用set方法即可
public class UserTest {
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        //调用set方法
        ((UserServiceImpl) userService).setUserDao(new UserDaoImpl());
        userService.getUser();
    }
}
  • 测试结果
    在这里插入图片描述
  • 总结

①之前,程序是主动创建对象,控制权在程序员手上,使用set注入之后,程序不再具有主动性,变成了被动的接收对象

②这种思想,从本质上解决了问题,程序员不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注的在业务的实现上,这是IOC的原型
在这里插入图片描述

IOC的本质

在这里插入图片描述
控制反转loC,是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入。

控制反转简单的例子

  • 新建一个maven项目,写一个实体类User
public class User {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • 在resources包下新建一个xml文件,名字就叫beans.xml吧,根据User实体类写一个bean,并使用property设置name属性的值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <!--
		相当于User hello = new User()
    		 hello.setName("zzy")
	-->
    <bean id="hello" class="com.zzy.pojo.User">
        <property name="name" value="zzy"/>
    </bean>
</beans>
  • 测试类UserTest,使用ClassPathXmlApplicationContext的构造方法解析配置文件,然后调用ApplicationContext接口中的getBean方法就可以获取到配置文件中的bean对象了
public class UserTest {
    public static void main(String[] args) {
        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //现在user对象就由spring管理了,要使用的话,直接取出即可
        User user = (User) context.getBean("hello");
        System.out.println(user.toString());
    }
}
  • 测试结果
    在这里插入图片描述

这个过程就叫控制反转:

  • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的

  • 反转:程序本身不创建对象,而变成被动的接收对象

  • 依赖注入:就是利用set方法来进行注入的

  • IOC是一种编程思想,由主动的编程变成被动的接收

  • 可以通过newClassPathXmIApplicationContext去浏览一下底层源码

使用IOC容器

将一开始那个例子使用spring提供的IOC容器进行修改

  • 新建beans.xml文件,将UserDaoImpl、UserMysqlDaoImpl和UserServiceImpl写做几个bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="daoImpl" class="com.zzy.dao.UserDaoImpl"/>
    <bean id="mysqlImpl" class="com.zzy.dao.UserMysqlDaoImpl"/>
    <!--
        ref:引用Spring容器中的对象
        value:具体的值
     -->
    <bean id="serviceImpl" class="com.zzy.service.UserServiceImpl">
        <property name="userDao" ref="mysqlImpl"/>
    </bean>
</beans>
  • 修改UserTest类
public class UserTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("serviceImpl");
        serviceImpl.getUser();
    }
}
  • 测试结果
    在这里插入图片描述
  • 到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓IOC,就是对象由Spring来创建,管理,装配

IOC创建对象的方式

默认使用无参构造

  • 创建实体类
public class User {
    private String name;
    private int age;

    //省略get set

    public void show(){
        System.out.println("name:" + name + " age:" + age);
    }
}
  • 和之前一样,创建beans.xml,配置bean,使用测试类得到bean,调用show方法
    在这里插入图片描述

如果想要使用有参构造创建对象

  • 添加构造函数
public User(String name, int age) {
    this.name = name;
    this.age = age;
}
  • 修改beans.xml配置文件

①使用下标的方式赋值

<bean id="user" class="com.zzy.pojo.User">
    <constructor-arg index="0" value="zzy"/>
    <constructor-arg index="1" value="20"/>
</bean>

②使用类型的方式赋值

<bean id="user" class="com.zzy.pojo.User">
    <constructor-arg type="java.lang.String" value="zzy"/>
    <constructor-arg type="int" value="20"/>
</bean>

③使用参数名的方式赋值

<bean id="user" class="com.zzy.pojo.User">
    <constructor-arg name="name" value="zzy"/>
    <constructor-arg name="age" value="20"/>
</bean>
  • 测试
    在这里插入图片描述

多个bean的情况

  • 我们再来创建一个实体类UserTwo,有一个无参构造,在创建这个对象的时候会打印东西
public class UserTwo {
    private String name;

    public UserTwo() {
        System.out.println("UserTwo对象被创建了!!!");
    }

    //省略get set
}
  • 修改beans.xml配置文件
<bean id="user" class="com.zzy.pojo.User">
    <constructor-arg name="name" value="zzy"/>
    <constructor-arg name="age" value="20"/>
</bean>

<bean id="userTwo" class="com.zzy.pojo.UserTwo">
    <property name="name" value="zzy"/>
</bean>
  • 在测试类中,我们调用getBean只获取user对象,不获取userTwo对象
public class UserTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
}
  • 测试结果,可以发现userTwo对象也被创建了
    在这里插入图片描述
  • 使用getBean得到两个user对象,使用==判断是否相等
    在这里插入图片描述
  • 说明:

在配置文件加载的时候,也就是ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml")这句话被执行的时候,Spring会把配置文件中的所有bean都进行初始化,默认放到一个对象池中,当我们调用getBean时,只是获取了某个对象的引用,不是创建对象

Spring配置

  • 别名
<!--如果添加了别名,我们也可以使用别名来获取到这个对象-->
<alias name="user" alias="userNew"/>
  • Bean的配置
<!--
id: bean的唯一标识符,也就是对象名
class:bean对象所对应的全限定名
name:别名,name可以同时取多个名字,使用逗号、空格、分号分隔都可以
-->
<bean id="user" class="com.zzy.pojo.User" name="user2,user3 user4;user5" />
  • import

一般用于团队开发,可以把多个配置文件合并为一个

假设现在项目中有多个人开发,分别负责不同的类的开发,不同的类需要注册到不同的xml中,可以利用import将所有人的xml合并为一个总的xml,使用时使用总的即可

<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

依赖注入

构造器注入

在IOC创建对象的方式那里已经说过了,包括无参构造和有参构造

set方式注入

依赖注入

依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入

环境搭建

  • 复杂类型
public class Address {
    private String address;

    //省略 get set toString
}
  • 真实测试对象
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String son;
    private Properties info;

    //省略get set toString
}
  • beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <bean id="stu" class="com.zzy.pojo.Student">
         <!--第一种 普通值注入 value-->
        <property name="name" value="zzy"/>
    </bean>
</beans>
  • 测试类
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student stu = (Student) context.getBean("stu");
        System.out.println(stu.getName());
    }
}
  • 完善注入信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="address" class="com.zzy.pojo.Address">
        <property name="address" value="邢台"/>
    </bean>
	
    <bean id="stu" class="com.zzy.pojo.Student">
        <!--普通值注入-->
        <property name="name" value="zzy"/>
        <!--引用注入-->
        <property name="address" ref="address"/>
        <!--数组注入-->
        <property name="books" >
            <array>
                <value>java</value>
                <value>C语言</value>
                <value>jvm</value>
            </array>
        </property>
        <!--map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="130555555555555"/>
                <entry key="银行卡" value="135545555555655"/>
            </map>
        </property>
        <!--set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>qq飞车</value>
                <value>gta5</value>
            </set>
        </property>
        <!--list注入-->
        <property name="hobbys">
            <list>
                <value>ctrl a</value>
                <value>ctrl c</value>
                <value>ctrl v</value>
            </list>
        </property>
        <!--null注入-->
        <property name="son">
            <null/>
        </property>
        <!--property注入-->
        <property name="info">
            <props>
                <prop key="学号">201911111111</prop>
                <prop key="班级">2班</prop>
                <prop key="专业">信息安全</prop>
            </props>
        </property>
    </bean>
</beans>
  • 测试结果
    在这里插入图片描述

拓展方式注入

  • P命名空间注入(对应set注入)和C命名空间注入(对应构造器注入)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       <!--p命名空间注入要导入的约束-->
       xmlns:p="http://www.springframework.org/schema/p"
	   <!--c命名空间注入要导入的约束-->
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入-->
    <bean id="user1" class="com.zzy.pojo.User" p:name="zzy" p:age="20"/>

    <!--c命名空间注入-->
    <bean id="user2" class="com.zzy.pojo.User" c:name="ysy" c:age="18"/>

</beans>
  • 测试
    在这里插入图片描述

Bean的作用域

在这里插入图片描述

  • 单例模式(Spring的默认机制,每次get拿出的都是同一个对象)
<bean id="user1" class="com.zzy.pojo.User" p:name="zzy" p:age="20" scope="singleton"/>
  • 原型模式(每次从容器中get的时候,都会产生一个新对象)
<bean id="user1" class="com.zzy.pojo.User" p:name="zzy" p:age="20" scope="prototype"/>
  • 其余的request、session、application,这些在web开发中会使用到

Bean的自动装配

自动装配

是Spring满足bean依赖的一种方式,会在上下文中自动寻找,并自动装配bean的属性

在Spring中有三种装配的方式:

  • 在xml中显示的配置
  • 在java中显示配置
  • 隐式的自动装配bean

环境搭建

public class Dog {
    public void shout(){
        System.out.println("汪汪汪");
    }
}
public class Cat {
    public void shout(){
        System.out.println("喵喵喵");
    }
}
public class People {
    private Cat cat;
    private Dog dog;
    private String name;

    //省略set get toString
}

byName自动装配

<bean id="cat" class="com.zzy.pojo.Cat"/>
<bean id="dog" class="com.zzy.pojo.Dog"/>

<!--
	byName:会自动在容器上下文中寻找和自己set方法后面的值对应的beanId
-->
<bean id="people" class="com.zzy.pojo.People" autowire="byName">
    <property name="name" value="zzy"/>
</bean>

byType自动装配

<bean class="com.zzy.pojo.Cat"/>
<bean class="com.zzy.pojo.Dog"/>
<!--
	byName:会自动在容器上下文中寻找和自己对象属性类型相同的bean
-->
<bean id="people" class="com.zzy.pojo.People" autowire="byType">
    <property name="name" value="zzy"/>
</bean>

注意

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致

使用注解实现自动装配

须知:

  • 导入约束,xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  • 配置注解的支持,<context:annotation-config/>
<?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">

    <context:annotation-config/>

</beans>

@Autowired

  • 配置文件编写
<?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">

    <!--开启注解的支持-->
    <context:annotation-config/>

    <bean id="cat" class="com.zzy.pojo.Cat"/>
    <bean id="dog" class="com.zzy.pojo.Dog"/>
    <bean id="people" class="com.zzy.pojo.People"/>

</beans>
  • People实体类添加@Autowired注解
public class People {
    @Autowired
    private Cat cat;
    
    @Autowired
    private Dog dog;
    
    private String name;

    //省略get set toString
}
  • 注意
  1. 直接在属性上使用即可!也可以在set方式上使用
  2. 使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字
  3. 如果Autowired的required属性为false,说明这个字段可以为null,否则不允许为空
  4. Autowired的原理是先byType自动装配,再byName自动装配
  5. 如果Autowired自动装配的环境比较复杂,xml配置文件中不存在唯一的beanId,可以使用@Qualifier(value=“xxx”)配合@Autowired使用,指定一个唯一的bean注入
<bean id="cat666" class="com.zzy.pojo.Cat"/>
<bean id="cat233" class="com.zzy.pojo.Cat"/>
@Autowired
@Qualifier("cat666")
private Cat cat;

@Resource

@Resource
private Cat cat;

@Resource(name = "dog1")
private Dog dog;
<bean id="cat" class="com.zzy.pojo.Cat"/>
<bean id="dog1" class="com.zzy.pojo.Dog"/>
<bean id="dog2" class="com.zzy.pojo.Dog"/>

@Autowired和@Resource的区别

  • 都是用来自动装配,都可以放在属性字段上
  • @Autowired是默认通过byType的方式,如果匹配到多个,使用byName进行装配,如果匹配不到,可以使用@Qualifier配合@Autowired使用来指定
  • @Resource是默认通过byName的方式,如果没有匹配到,使用byType进行装配,如果匹配到多个,可以通过@Resource上的name属性来指定

使用注解开发

在Spring4之后,要使用注解开发,必须要保证AOP的包导入了
使用注解必须要导入context约束,增加注解支持

<?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">

    <!--开启注解的支持-->
    <context:annotation-config/>
</beans>

扫描实体类的包

<!-- 添加component-scan支持,可以扫描某个包下所有类的@Component注解-->
<context:component-scan base-package="com.zzy.pojo"/>
//添加@Component注解,这样Spring就可以扫描到这个类
@Component
public class User {
    public String name = "zzy";
}

属性如何注入

@Component
public class User {

    //相当于<property name="name" value="zzy"/>,也可也放在set方法上
    //如果实体类较为复杂,建议还是用配置文件
    @Value("zzy")
    public String name;

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

衍生的注解

@Component有几个衍生的注解,在web开发中,会按照mvc三层架构分层

  • dao:@Repository
  • service:@Service
  • controller:@Controller
  • 记得修改component-scan扫描的包路径,要全部包括
  • 这四个注解功能都是一样的,都代表将某个类注册到Spring中,装配Bean

自动装配的注解

@Autowired:

通过byType的方式自动装配,如果匹配到多个,使用byName进行装配,如果匹配不到,可以使用@Qualifier配合@Autowired使用来指定

@Resource:

通过byName的方式自动装配,如果没有匹配到,使用byType进行装配,如果匹配到多个,可以通过@Resource上的name属性来指定

作用域

@Scope:标注使用哪种作用域

@Component
@Scope(value = "prototype")
public class User {
    @Value("zzy")
    public String name;
}

总结

xml与注解

  • xml更加万能,适用于任何场合,维护简单方便
  • 注解,不是自己类使用不了,维护相对复杂

xml与注解最佳实践

  • xml用来管理bean
  • 注解只负责属性的注入
  • 要让注解生效,必须要开启注解的支持
<!--开启注解的支持-->
<context:annotation-config/>
<context:component-scan base-package="com.zzy"/>

使用java的方法配置Spring

完全不使用Spring xml的配置,全权交给java

@ComponentScan + @Component

  • Config配置类
@ComponentScan("com.zzy")
public class MyConfig {
}
  • User实体类
@Component
public class User {
    @Value("zzy")
    private String name;

    //省略set get toString
}

@Configuration + @Bean

  • Config配置类
@Configuration
public class MyConfig {

    @Bean
    public User user() {
        return new User();
    }
}
  • User实体类
public class User {
    @Value("zzy")
    private String name;

    //省略set get toString
}

测试

public class Test {
    public static void main(String[] args) {
        ApplicationContext myConfig = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = myConfig.getBean("user", User.class);
        System.out.println(user.getName());
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值