初识springIOC

    xiaoxiao2021-03-26  7

    package cn.itcast.a_hello; public class User { private int id; private String name; public User() { super(); System.out.println("------User对象创建------"); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void init_user() { System.out.println("创建对象之后,初始化"); } public void destroy_user() { System.out.println("IOC容器销毁,user对象回收!"); } } public class App1_get_ioc { //2. (方便)直接得到IOC容器对象 @Test public void testAc() throws Exception { // 得到IOC容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/a_hello/applicationContext.xml"); // 从容器中获取bean User user = (User) ac.getBean("user"); System.out.println(user); } } 与测试类同一目录下applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- IOC容器的配置: 要创建的所有的对象都配置在这里 <bean id="user" class="cn.itcast.a_hello.User" init-method="init_user" destroy-method="destroy_user" scope="singleton" lazy-init="false"></bean> --> <bean id="user" class="cn.itcast.a_hello.User"></bean> </beans> 问:spring配置文件中,bean节点的id与name属性的区别? <bean id="test" name="1test" class="cn.itcast.b_create_obj.User"></bean>答:id 不能有特殊符号, 且唯一,且不能以数字开始。name 可以有特殊符号

    转载请注明原文地址: https://ju.6miu.com/read-650334.html

    最新回复(0)