1.创建maven项目:
2.使用maven下载spring,增加的配置如下:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.6.RELEASE</version> </dependency>
3.创建User类
User.java
package com.shuoeasy.test; public class User { private String name; public void setName(String name){ this.name = name; } public void hello(){ System.out.println("你好:" + this.name); } }
4.创建spring配置文件
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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userHello" class="com.shuoeasy.test.User"> <property name="name" value="老鹰开灰机"></property> </bean> </beans>
5.创建Main类
Main.java
package com.shuoeasy.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // 1.创建Spring的IOC容器对象 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 2.从IOC容器中获取Bean实例 User user = (User) ctx.getBean("userHello"); // 3.调用 user.hello(); } }
6.运行
7.原理