栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IOC操作Bean管理(XML自动装配)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IOC操作Bean管理(XML自动装配)

文章目录

一、什么是自动装配(自动装配只针对对象类型)

二、自动装配的过程

1.引入依赖

2.创建两个类(User和School)

3.配置bean.xml

4.测试结果

一、什么是自动装配(自动装配只针对对象类型)

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

二、自动装配的过程

1.引入依赖

        
            org.springframework
            spring-beans
            5.2.5.RELEASE
        
        
            org.springframework
            spring-core
            5.2.5.RELEASE
        
        
            org.springframework
            spring-context
            5.2.5.RELEASE
        
        
            junit
            junit
            4.13.1
            test
        
    

2.创建两个类(User和School)

代码如下(示例):

public class User {
    private String name;
    private Integer age;
    private School school;

    public void add(){
        System.out.println("user add 方法。。。。。");
    }
public class School {
    private User user;

    public void add(){
        System.out.println("school add 方法。。。。");
    }

3.配置bean.xml

因为自动xml自动装配只适用于对象类型的自动装配,所以一般类型的属性值用之前的方式注入即可,否则将没有值




    
    
        
        
    
    

    

4.测试结果
@Test
    public void test(){
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        User user = context.getBean(User.class);
        System.out.println(user.getName());
        user.getSchool().add();
        System.out.println("****************");
        School school= context.getBean(School.class);
        school.getUser().add();
    }

如有不足或可以改进之处,还望指正,可以一起交流!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/839108.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号