2、构造器注入
在我的前面博客里面,讲到了构造器。
参考:https://blog.youkuaiyun.com/beyond_csdn/article/details/115098064
3、拓展方式注入
3.1、p命名空间注入
-
编写实体类;
package com.beyond.pojo; public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
-
编写bean.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p命名空间注入,可以直接注入属性值相当于property--> <bean id="user" class="com.beyond.pojo.User" p:name="遇见狂神说" p:age="16"/> </beans>
-
测试。
import com.beyond.pojo.Student; import com.beyond.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); User user = context.getBean("user", User.class); System.out.println(user); } }
3.2、c命名空间
-
编写实体类;
package com.beyond.pojo; public class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
-
编写bean.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:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--c命名空间注入,通过构造器注入相当于constructor-arg--> <bean id="user2" class="com.beyond.pojo.User" c:_0="秦疆" c:age="18"/> </beans>
-
测试。
import com.beyond.pojo.Student; import com.beyond.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); User user = context.getBean("user2", User.class); System.out.println(user); } }
注意:p命名空间和c命名空间不能直接使用,需要在bean.xml中导入约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"