初学Spring(1)
新建问候接口
?
package com.shunwang.spring;public interface GreetingService {public void sayGreeting();}?接口的实现类
?
package com.shunwang.spring;public class GreetingServiceImpl implements GreetingService{private String greeting;public String getGreeting() {return greeting;}public void setGreeting(String greeting) {this.greeting = greeting;}public void sayGreeting(){System.out.println(greeting);}public GreetingServiceImpl(){}public GreetingServiceImpl(String greeting){this.greeting = greeting;}}?
spring配置文件 hello.xml放在src目录下
在<bean>元素中,<property>元素表示设置属性值。? 例如此处:使用<property>,告诉Spring容器通过Bean的setGreeting()方法来设置其属性值.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org//dtd/spring-beans.dtd"><!--通过set方法注入--><beans><bean id="greetingService"name="code">package com.shunwang.spring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class HelloApp {public static void main(String[] args) throws Exception{ApplicationContext context = new ClassPathXmlApplicationContext("hello.xml");GreetingService greetingService = (GreetingService)context.getBean("greetingService");greetingService.sayGreeting();}}?