package org.zcs.spring;import org.springframework.beans.factory.BeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;publicclassDrawingApp{publicstaticvoidmain(String[] args){// TODO Auto-generated method stub//BeanFactory factory = new FileSystemXmlApplicationContext("src/spring.xml");//Triangle triangle = new Triangle();
ApplicationContext context =newClassPathXmlApplicationContext("spring.xml");
Triangle triangle =(Triangle)context.getBean("triangle");
triangle.draw();}}
Triangle.java
package org.zcs.spring;publicclassTriangle{private String type;privateint height;publicintgetHeight(){return height;}publicvoidsetHeight(int height){this.height = height;}public String getType(){return type;}publicTriangle(String type ){this.type = type;}publicTriangle(int height){this.height = height;}publicTriangle(String type,int height){this.type = type;this.height = height;}publicvoidsetType(String type){this.type = type;}publicvoiddraw(){
System.out.println(getType()+" : There is a triangle. "+getHeight());}}
spring.xml(根据索引注入)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "triangle" class= "org.zcs.spring.Triangle" >
<constructor-arg index = "0" value = "this is three say"></constructor-arg>
<constructor-arg index = "1" value = "20"></constructor-arg></bean></beans>
spring.xml(根据类型注入)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "triangle" class= "org.zcs.spring.Triangle" >
<constructor-arg type = "int" value = "50"></constructor-arg></bean></beans>
spring.xml(传入按顺序两个参数)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "triangle" class= "org.zcs.spring.Triangle" >
<constructor-arg value = "this is three say"></constructor-arg>
<constructor-arg value = "20"></constructor-arg></bean></beans>