详见四、IOC创建对象
Spring-IOC创建对象的方式_xmosang的博客-CSDN博客
6.2、Set方式注入【重点】-
依赖注入
-
依赖:bean对象的创建依赖于容器
-
注入:bean对象中的所有属性,由容器来注入
-
【环境搭建】
-
pojo:
package com.mosang.pojo; import lombok.Data; import java.util.*; @Data public class Student { { private String name; private Address address; private String[] book; private Listhobby; private Map card; private Set games; private String girlfriend; private Properties properties; @Override public String toString() { return "Student{" + "name='" + name + ''' + ", address=" + address.toString() + ", book=" + Arrays.toString(book) + ", hobby=" + hobby + ", card=" + card + ", games=" + games + ", girlfriend='" + girlfriend + ''' + ", properties=" + properties + '}'; } } @Data public class Address { private String name; private int id; }
-
xml配置
西游记 红楼梦 水浒传 三国演义
写病毒 读书 玩游戏 LOL CSGO CF root 123456
-
环境测试
import com.mosang.pojo.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; 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.toString()); } }
-
结果
1. p-namespace:p命名空间 :
- 官方解释:
- XML Shortcut with the p-namespace
- 使用:
2. c-namespace:c命名空间
- 官方解释:
- XML Shortcut with the c-namespace
- 使用:
注意
p-namespace和c-namespace不能直接使用,需要导入xml约束
测试:
@Test public void ttt(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); user user = context.getBean("user", user.class); user user1 = context.getBean("user", user.class); System.out.println(user==user1); }6.4、bean的作用域
1. 单例模式(Spring默认)
每次从容器中get,产生的对象都是同一个
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); user user = context.getBean("user", user.class); user user1 = context.getBean("user", user.class); System.out.println(user==user1);
2. 原型模式:
每次从容器中get的时候,都会产生一个新的对象
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); user user = context.getBean("user", user.class); user user1 = context.getBean("user", user.class); System.out.println(user==user1);
3. 其他模式:request、session、application只会在web开发中使用到
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)