在前面的文章中,提到了在Spring
中注入有构造器注入和Set
方式注入,并且均对这两种注入进行了简单的案例实践。这里对于以上的两种注入方式,有两种比较简单的写法。
1. 对于构造器注入
在官方文档中叫c-namespace
,对应前面学过的构造器注入方式。官方文档地址:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-c-namespace
首先需要引入约束xmlns:c="http://www.springframework.org/schema/c"
,然后使用c:
使用,如,User.java
中定义:
private int age;
private String name;
public User() {
}
public User(int age, String name) {
this.age = age;
this.name = name;
}
并生成对应的get
、set
和toString
方法,然后,我们在beans.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">
<bean id="weizu" class="com.weizu.pojo.User" c:age="12" c:name="战三"></bean>
</beans>
测试:
public class myTest {
@Test
public void Test(){
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User userService = (User) context.getBean("weizu");
System.out.println(userService.toString());
}
}
2. Set
版本
使用p-namespace
来进行简化。set
属性注入默认使用无参构造函数,然后使用set
方法来进行值的注入。地址:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace。类似的,需要先引入约束:xmlns:p="http://www.springframework.org/schema/p"
,然后p:
。使用案例:
<?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">
<bean id="weizu" class="com.weizu.pojo.User" p:age="12" p:name="战三"></bean>
</beans>
测试函数不变,结果: