Spring知识小汇(4)——依赖注入(构造器注入、set方式注入、扩展方式注入)
发布日期:2021-05-07 08:59:24 浏览次数:28 分类:精选文章

本文共 3240 字,大约阅读时间需要 10 分钟。

文章目录

依赖注入

  • 依赖:依赖于spring容器
  • 注入:对于创建的对象,可以对其属性进行注入,或者注入其他对象

构造器注入

set方式注入【重点】

pojo

public class Student {       private String name;    private Address address;    private String[] books;    private List
hobbies; private Map
card; private Set
games; private String bf; private Properties info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String[] getBooks() { return books; } public void setBooks(String[] books) { this.books = books; } public List
getHobbies() { return hobbies; } public void setHobbies(List
hobbies) { this.hobbies = hobbies; } public Map
getCard() { return card; } public void setCard(Map
card) { this.card = card; } public Set
getGames() { return games; } public void setGames(Set
games) { this.games = games; } public String getBf() { return bf; } public void setBf(String bf) { this.bf = bf; } public Properties getInfo() { return info; } public void setInfo(Properties info) { this.info = info; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address + ", books=" + Arrays.toString(books) + ", hobbies=" + hobbies + ", card=" + card + ", games=" + games + ", bf='" + bf + '\'' + ", info=" + info + '}'; }}

beans.xml

水浒传
红楼梦
三国演义
西游记
code
code
code
lol
eat chicken
...
...
...
...

test

public class MyTest {       public static void main(String[] args) {           ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        Student student = (Student) context.getBean("student");        System.out.println(student);/** Student{ name='www', address=Address{address='sh'}, books=[水浒传, 红楼梦, 三国演义, 西游记], hobbies=[code, code, code], card={身份证=..., 银行卡=...}, games=[lol, eat chicken], bf='null', info={password=..., url=..., driver=..., username=...}} **/    }}

扩展方式注入

p命名空间和c命名空间

如有不对的地方欢迎指出,共同进步!

上一篇:element——表单的使用(置空、校验)
下一篇:vue ref的基本使用

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月03日 06时30分21秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章