1.对象依赖注入 2.利用setter实现静态数值的注入 2.1 pom.xml dependency groupIdorg.springframework/groupId artifactIdspring-context/artifactId version5.2.6.RELEASE/version /dependency 2.2 resource目录下创建applicationCont
1.对象依赖注入
2.利用setter实现静态数值的注入
2.1 pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
2.2 resource目录下创建applicationContext.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--Ioc容器自动利用反射机制运行时调用setXXXX方法自动为属性赋值-->
<bean id="sweetApple" class="com.imooc.spring.ioc.entity.Apple">
<property name="title" value="红富士"/>
<property name="origin" value="欧洲"/>
<property name="color" value="红色"/>
<property name="price" value="5555.225"/>
</bean>
</beans>
2.3 测试类
package com.imooc.spring.ioc;
import com.imooc.spring.ioc.entity.Apple;
import com.imooc.spring.ioc.entity.Child;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringApplication
{
public static void main(String[] args)
{
//创建SpringIoc容器,并根据配置文件在容器中实例化
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Apple sweetApple = context.getBean("sweetApple", Apple.class);
System.out.println(sweetApple.getTitle());
}
}
3. 利用setter方法实现对象注入
3.1 示例
3.2 resource目录下创建applicationContext.xml ref="sweetApple"
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--Ioc容器自动利用反射机制运行时调用setXXXX方法自动为属性赋值-->
<bean id="sweetApple" class="com.imooc.spring.ioc.entity.Apple">
<property name="title" value="红富士"/>
<property name="origin" value="欧洲"/>
<property name="color" value="红色"/>
<property name="price" value="5555.225"/>
</bean>
<bean id="lily" class="com.imooc.spring.ioc.entity.Child">
<property name="name" value="lili"/>
<!--利用ref注入依赖对象-->
<property name="apple" ref="sweetApple"/>
</bean>
</beans>