创建一个HelloWorld项目
1.导入Spring的Java包:
2.配置applicationContext.xml文件
注:可以下在spring tool插件使开发更轻松!
3.编写applicationContext.xml文件,并添加相应的标签。这个applicationContext.xml即为IOC容器
<?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="hello" class="com.ming.bean.HelloWorld">
<!-- 使用构造器的方式注入,根据参数列表的的不同,IOC容器自动调用不同的构造器 -->
<constructor-arg value="ming" type="java.lang.String"></constructor-arg>
<constructor-arg value="hubei" type="java.lang.String"></constructor-arg>
<constructor-arg value="21" type="int"></constructor-arg>
</bean>
</beans>
4.使用IOC容器创建实例
public class Main {
public static void main(String[] args) {
/* 原始方式,创建一个对象,直接通过new的方式,这样的代码的耦合度很高。
* HelloWorld hello = new HelloWorld();
* hello.setName("ming");
* hello.sayHello();
*/
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld h1 = (HelloWorld) context.getBean("hello");
System.out.println(h1);
}
}
来源:CSDN
作者:jie_ming514
链接:https://blog.csdn.net/m1090760001/article/details/104582631