0
点赞
收藏
分享

微信扫一扫

Spring实现简单IoC


使用Spring框架的​​IoC​​可以通过配置xml和反射机制实现。

下载springframework

​​https://repo.spring.io/ui/repos/tree/Builds/libs-release-local/org/springframework/spring/5.2.9.RELEASE/spring-5.2.9.RELEASE-dist.zip​​​ 或
https://repo.spring.io/ui/native/libs-release-local/org/springframework/spring/5.3.9/

定义接口和实现类

public interface IHello {
public String sayHello(String name);
}

public class HelloChina implements IHello {
@Override
public String sayHello(String name) {
return "你好, " + name + "先生";
}
}

public class HelloEnglish implements IHello{
@Override
public String sayHello(String name) {
return "How are you " + name;
}
}

使用XML配置Bean

在resources目录下新建​​bean.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloBean" class="HelloChina"></bean>
</beans>

通过实例IoC容器读取Bean

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class One {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
IHello hi = (IHello) context.getBean("helloBean");
String hello = hi.sayHello("Kitty");
System.out.printf(hello);
}
}

Spring实现简单IoC_ide

配置bean为:​​<bean id="helloBean" class="HelloEnglish"></bean>​​:

Spring实现简单IoC_java_02


举报

相关推荐

0 条评论