使用Spring管理Bean也称依赖注入( Dependency Injection, DI ),通过这种方式将Bean的控制权交给Spring
在使用Spring实例化一个对象时,无论类是否有参数都会默认调用对象类的无参构造,对于有参数的情况,Spring有两种方式可以带参实例化
示例类 Shape
public class Shape {
private Integer width;
private Integer height;
public Shape() {
System.out.println("运行了Shape的无参构造");
}
public Shape(Integer width, Integer height) {
this.width = width;
this.height = height;
System.out.println("运行了Shape的有参构造");
}
public Integer getHeight() {
return height;
}
public Integer getWidth() {
return width;
}
public void setHeight(Integer height) {
this.height = height;
}
public void setWidth(Integer width) {
this.width = width;
}
@Override
public String toString() {
return "Width: " + this.width + "\tHeight:" + this.height;
}
}
主函数
public class Demo {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Shape shape = (Shape)applicationContext.getBean("Shape");
System.out.println(shape);
}
}
applicationContext.xml
通过Setter实例化
<?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="Shape" class="learn.test.Shape">
<!-- property标签会自动调用Setter -->
<property name="width" value="200"></property>
<property name="height" value="500"></property>
</bean>
</beans>
运行结果
运行了Shape的无参构造
Width: 200 Height:500
通过类带参构造实例化
<?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="Shape" class="learn.test.Shape">
<!-- constructor-arg标签调用带参构造 -->
<constructor-arg name="width" value="200"></constructor-arg>
<constructor-arg name="height" value="500"></constructor-arg>
</bean>
</beans>
运行结果:
运行了Shape的有参构造
Width: 200 Height:500
原文地址:https://www.cnblogs.com/esrevinud/p/11747355.html
时间: 2024-11-03 01:22:31