package com.sevenhu.domain; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by hu on 2016/3/31. */ public class HelloWorld { private String userName; //Spring项目中,配置在容器中的类,其属性都必须有setter方法 public void setUserName(String userName) { this.userName=userName; } public void hello(){ System.out.println("Hello: "+userName); } public static void main(String[] args){ //1.创建Spring的IOC容器 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml"); //2.从容器中获取bean HelloWorld helloWorld= (HelloWorld) applicationContext.getBean("helloWorld"); System.out.println(helloWorld); //3.调用方法 helloWorld.hello(); } }
Spring的配置文件的代码如下:
<?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="helloWorld" class="com.sevenhu.domain.HelloWorld"> <property name="userName" value="Spring"></property> </bean> </beans>