spring 依赖注入
感觉相当于把原来的在代码中赋值改成在xml配置文件中赋值
1 set注入
1 //需要注入的类 2 package beans; 3 public class HelloWorld { 4 private String msg = null; 5 public String getMsg() { 6 return msg; 7 } 8 public void setMsg(String msg) { 9 this.msg = msg; 10 } 11 }
1 <!--spring-config.xml 配置文件--> 2 <?xml version="1.0" encoding="UTF-8"?> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!--这里进行注入,其中id值就是测试类中getBean方法里的参数,property的name值就是被注入类中的变量名--> 7 <bean id="HelloWorld" class="beans.HelloWorld"> 8 <property name="msg" value="HelloWorld"/> 9 </bean> 10 </beans>
1 //测试类 2 import beans.HelloWorld; 3 import org.junit.Test; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 public class SpringTest { 7 @Test 8 public void beanTest() { 9 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml"); 10 HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("HelloWorld"); 11 System.out.println(helloWorld.getMsg()); 12 } 13 }
2 构造函数注入
1 //需要注入的类 2 package beans; 3 public class HelloWorld { 4 private String msg = null; 5 public HelloWorld(String msg) { 6 this.msg = msg; 7 } 8 public String getMsg() { 9 return msg; 10 } 11 }
1 <!--spring-config.xml 配置文件--> 2 <?xml version="1.0" encoding="UTF-8"?> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!--index值表示构造函数中的第几个参数,从0开始数--> 7 <bean id="HelloWorld" class="beans.HelloWorld"> 8 <constructor-arg index="0" value="Hello Constructor"/> 9 </bean> 10 </beans>
测试类同上

浙公网安备 33010602011771号