使用Spring管理Bean也称依赖注入( Dependency Injection, DI ),经过这种方式将Bean的控制权交给Springjava
在使用Spring实例化一个对象时,不管类是否有参数都会默认调用对象类的无参构造,对于有参数的状况,Spring有两种方式能够带参实例化spring
示例类 Shapeapp
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.xmlide
<?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>
运行结果:this
运行了Shape的有参构造 Width: 200 Height:500