spring5之关于ioc的一些基本操作

讲之说的ioc和aop补上

spring中两大核心ioc和aop,ioc定义叫:控制反转。但根据我学下来,根据尚硅谷的讲解,我理解的是将对象交给spring进行管理,对象创建,属性注入等等,目的是解耦,方便管理,简化代码,它是基于工厂模式实现的,理解不到为还请多多包涵。

接下来进行一些简单的ioc的操作,它有注解和xml两种实现方式,首先根据xml配置文件来操作

首先是几个实体类

public class Book {
    private String bname;
    private String address;

    public void setAddress(String address) {
        this.address = address;
    }

    //set方法注入
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void shuchu(){
        System.out.println(bname);
    }
    public void shuchu1(){
        System.out.println(bname+","+address);
    }
}
public class Order {
    private String oname;
    private String address;

    public Order(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }
    public void test(){
        System.out.println(oname+","+address);
    }
}
public class User {
    private String username;

    public void add() {
        System.out.println("asdqw");
    }
}
View Code

然后是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 http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    对象注入-->
    <bean id="user" class="Spring5_test_class.User">
    </bean>

<!--    set方法注入属性-->
    <bean id="book" class="Spring5_test_class.Book">
<!--        使用property完成属性的注入-->
        <property name="bname" value="红楼梦"></property>
<!--        设置固定值null-->
<!--        <property name="address">-->
<!--            <null></null>-->
<!--        </property>-->
<!--        设置属性值中包含特殊符号,把特殊符号内容写到CDATA-->
        <property name="address">
            <value>
                <![CDATA[<<北京>>]]>
            </value>
        </property>
    </bean>



<!--    有参数构造注入属性-->
    <bean id="orders" class="Spring5_test_class.Order">
        <constructor-arg name="oname" value="abc"></constructor-arg>
        <constructor-arg name="address" value="中国"></constructor-arg>
    </bean>

</beans>
View Code

测试:

public class TestSpring5 {

    @Test
    public void testadd() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //获取配置的创建对象
        User user1 = context.getBean("user", User.class);
        user1.add();
        System.out.println(user1);
    }
    @Test
    public void testbook(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        //获取配置的创建对象
        Book book= context.getBean("book", Book.class);
        book.shuchu1();
    }
    @Test
    public void testorder(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        //获取配置的创建对象
        Order order= context.getBean("orders", Order.class);
        order.test();
    }
}
View Code

今天这只是一个简单属性注入,之后在补上外部bean注入,级联赋值等等

posted @ 2022-04-07 20:28  chenghaixinag  阅读(27)  评论(0编辑  收藏  举报