`
qqbwww
  • 浏览: 59371 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

初学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"
		class="com.shunwang.spring.GreetingServiceImpl">
		<property name="greeting">
			<value>Buenos Dias!</value>
		</property>	
	</bean>
	
<!--通过构造方法注入
	<bean id="greetingServie" class="com.shunwang.spring.GreetingServiceImpl">
		<constructor-arg>
			<value>Buenos Dias!</value>
		</constructor-arg>
	</bean>
-->
 </beans>

 

主类

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();
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics