使用Spring创建HelloWorld项目

半城伤御伤魂 提交于 2020-03-01 07:52:53

创建一个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);
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!