1.首先新建一个Maven项目
2.到底怎么创建我就不说了,网上资料一大把
在pom.xml文件中引入四个主要jar包,
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
</dependencies>
之后在创建一个接口,一个实现类,一个测试类
package com.hyc.ioc.demo1;
public interface IUserService {
void sayHello();
}
package com.hyc.ioc.demo1;
public class UserService implements IUserService{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello(){
System.out.println("Hello Spring IOC!"+getName());
}
}
之后在resources文件夹下配置xml文件,如果没有resources文件夹的话就新建一个吧
<?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">
<!-- id标识,calss是类路劲 -->
<bean id="userService" class="com.hyc.ioc.demo1.UserService">
<!--(1)依赖注入,配置当前类中相应的属性-->
<property name="name" value="李四" />
</bean>
</beans>
测试:
package com.hyc.ioc.demo1;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo1 {
/**
* 传统开发方式
*/
public void demo1(){
IUserService userService=new UserService();
userService.sayHello();
}
/**
* spring依赖注入
*/
@Test
public void demo2(){
//创建Spring的工厂
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//通过工厂模式获得类
IUserService userService= (IUserService) applicationContext.getBean("userService");
userService.sayHello();
}
}
测试结果:Hello Spring IOC!李四