
13

spring | 构造注入
source link: https://benpaodewoniu.github.io/2023/01/15/spring33/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

spring | 构造注入
注入: 通过 spring
的配置文件,为成员变量赋值。
Set
注入: Spring
调用 set
方法,通过配置文件为成员变量赋值。
构造注入: Spring
调用构造方法,通过配置文件,为成员变量赋值。
创建一个 person
类。
package com.rhino;
import lombok.Getter;
public class Person {
private Integer id;
@Getter
private String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
}
然后 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.rhino.Person">
<constructor-arg index="0" value="1"/> <!--数目和构造方法数目一样-->
<constructor-arg index="1" value="小明"/>
</bean>
</beans>
import com.rhino.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestFunction {
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
Person person = (Person) ctx.getBean("person");
System.out.println(person.getName());
}
}
构造方法重载
- 参数个数不同
- 通过
constructor-arg
数目进行区分
- 通过
相同数目的参数。
package com.rhino;
import lombok.Getter;
public class Person {
private Integer id;
@Getter
private String name;
public Person(Integer id) {
this.id = id;
}
public Person(String name) {
this.name = name;
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.rhino.Person">
<constructor-arg index="0" value="小明" type="java.lang.String"/>
</bean>
</beans>
使用 type
进行区分。
</div
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK