七、利用setter实现对象依赖注入
作者:互联网
依赖注入是指运行时将容器内对象利用反射赋给其他对象的操作,依赖注入有两种形式 1.基于setter方法注入对象 2.基于构造方法注入对象。
基于setter方法注入对象包含两种使用场景
1.利用setter实现静态数值注入(value)
<?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="sweetApple" class="com.spring.ioc.entity.Apple"> <!--IoC容器自动利用反射机制运行时调用setXXX方法为属性赋值--> <property name="title" value="红富士"></property> <property name="color" value="红色"></property> <property name="origin" value="欧洲"></property>
<property name="price" value="19.8"></property> </bean> </beans>
package com.spring.ioc; import com.spring.ioc.entity.Apple; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringApplication { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); Apple sweetApple = context.getBean("sweetApple", Apple.class); System.out.println(sweetApple.getTitle()); } }
//Apple的setTitle方法
/*public void setTitle(String title) {
System.out.println("title属性设置为:"+title);
this.title = title;
}*/
springIoC会将value中字符串自动转换成目标属性的类型,比如Intege
2.利用setter方法实现对象注入(ref)
<?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="sweetApple" class="com.spring.ioc.entity.Apple"> <!--IoC容器自动利用反射机制运行时调用setXXX方法为属性赋值--> <property name="title" value="红富士"></property> <property name="color" value="红色"></property> <property name="origin" value="欧洲"></property> <property name="price" value="19.8"></property> </bean> <bean id="lily" class="com.spring.ioc.entity.Child"> <property name="name" value="莉莉"></property> <!--利用ref注入依赖对象--> <property name="apple" ref="sweetApple"></property> </bean> </beans>
package com.spring.ioc; import com.spring.ioc.entity.Apple; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringApplication { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); Apple sweetApple = context.getBean("sweetApple", Apple.class); //System.out.println(sweetApple.getTitle()); } }
标签:依赖,Apple,sweetApple,context,import,setter,public,注入 来源: https://www.cnblogs.com/nanfeng66/p/16177143.html