Spring HelloWorld(1)

项目工程目录结构:

package com.yiibai.tutorial.spring.helloworld.impl;


import com.yiibai.tutorial.spring.helloworld.HelloWorld;
  
public class SpringHelloWorld implements HelloWorld {
  
    public void sayHello() {
        System.out.println("Spring Say Hello!!");
    }
  
}

 

package com.yiibai.tutorial.spring.helloworld.impl;


import com.yiibai.tutorial.spring.helloworld.HelloWorld;
  
public class StrutsHelloWorld implements HelloWorld {
  
    public void sayHello() {
        System.out.println("Struts Say Hello!!");
    }
  
}

 

package com.yiibai.tutorial.spring.helloworld;

public interface HelloWorld {
    public void sayHello();
}
package com.yiibai.tutorial.spring.helloworld;

public class HelloWorldService {
   //只是预留的接口,不必将代码写死了
    private HelloWorld helloWorld;
  
    public HelloWorldService() {
  
    }
  
    public void setHelloWorld(HelloWorld helloWorld) {
        this.helloWorld = helloWorld;
    }
  
    public HelloWorld getHelloWorld() {
        return this.helloWorld;
    }
  
}
package com.yiibai.tutorial.spring;
  
import com.yiibai.tutorial.spring.helloworld.HelloWorld;
import com.yiibai.tutorial.spring.helloworld.HelloWorldService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
public class HelloProgram {
  
     
    public static void main(String[] args) {
        //加载那些bean文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
         
        HelloWorldService service =
             (HelloWorldService) context.getBean("helloWorldService");
        //根据Bean文件实际依赖的对象得到返回值
        HelloWorld hw= service.getHelloWorld();
         
        hw.sayHello();
    }
}
<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="springHelloWorld"
        class="com.yiibai.tutorial.spring.helloworld.impl.SpringHelloWorld"></bean>
    
    <bean id="strutsHelloWorld"
        class="com.yiibai.tutorial.spring.helloworld.impl.StrutsHelloWorld"></bean>
  
  
    <bean id="helloWorldService"
        class="com.yiibai.tutorial.spring.helloworld.HelloWorldService">
     <!--这里利用的反射--> <property name="helloWorld" ref="strutsHelloWorld" /> </bean> </beans>

 

 

posted on 2017-04-25 14:45  老曹123  阅读(160)  评论(0)    收藏  举报

导航