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

Spring 使用自动装配的同时手动赋值会怎么样?

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

Spring 使用自动装配的同时手动赋值会怎么样?

在 Spring 中我们可以使用自动装配来初始化对象的属性,如果我们使用 autowire 的同时又通过 property 手动为属性赋值时会怎么样呢?(xml 配置方式)答案是:只会执行手动赋值。如:

public class Dog {
    private String name;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + ''' +
                '}';
    }
}
public class People {
    private Dog dog;
    
    public Dog getDog() {
        return dog;
    }
    
    public void setDog(Dog dog) {
        System.out.println("People.setDog(" + dog.getName() + ")");
        this.dog = dog;
    }
}

    


    



    

public class MyTest {
    @Test
    public void testAutowire() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans1.xml");
        People people = context.getBean("people", People.class);
        System.out.println(people.getDog());
    }
}

运行结果:

setDog 方法只被执行了一次。
而如果我们采用注解的方式,则会有所不同:

public class People {
    @Autowired
    private Dog dog = null;
    
    public Dog getDog() {
        return dog;
    }
}



    



输出结果:

(注意到上面的 People 类没有 setDog 方法,可见,使用注解时不是通过 set 方法设置值的)

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

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

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