1.spring最简单的例子
该例子展示如何配置一个Bean,并将一个字符串注入到Bean的属性中
接口
public interface GreetingService { public void sayGreeting(); } |
public class GreetingServiceImpl implements GreetingService { private String greeting; public GreetingServiceImpl() {} public GreetingServiceImpl(String greeting) { this.greeting = greeting; } public void sayGreeting() { System.out.println(greeting); } public void setGreeting(String greeting) { this.greeting = greeting; } } |
public class HelloApp { static GreetingServiceImpl greetService=new GreetingServiceImpl();//new一个实现类对象 public static void main(String[] args) throws Exception { greetService.setGreeting("hello word!");//调用时写死 greetService.sayGreeting(); } } |
<bean id="greetingService" class="com.springinaction.chapter01.hello.GreetingServiceImpl"> <property name="greeting" value="Buenos Dias!" /> </bean> |
使用了spring后的HelloApp可以这样写
public class HelloApp { public static void main(String[] args) throws Exception { BeanFactory factory = new XmlBeanFactory(new ClassPathResource("hello.xml"));//将hello.xml文件载入spring容器BeanFaction GreetingService greetingService = (GreetingService) factory.getBean("greetingService");//通过getbean方法得到Bean对应的服务 greetingService.sayGreeting();//调用服务的方法 } } |
这是spring最简单的一个应用,但是却展示出了在Spring中如何配置和使用一个类。
2.使用DI将一个Bean注入到另一个Bean
圆桌骑士类
public class KnightOfTheRoundTable implements Knight { private String name;//骑士名字 private Quest quest;//骑士任务,这里使用接口来声明,可以分配各种实现了该接口的任务 public KnightOfTheRoundTable(String name) { this.name = name; } //获取任务 public Object embarkOnQuest() throws QuestFailedException { return quest.embark(); } public void setQuest(Quest quest) { this.quest = quest; } public String getName() { return name; } } |
public interface Quest { public Object embark() throws QuestFailedException; } |
public class HolyGrailQuest implements Quest { public HolyGrailQuest() {} public Object embark() throws GrailNotFoundException { // do whatever it means to embark on a quest return new HolyGrail(); } } |
<bean id="quest" class="com.springinaction.chapter01.knight.HolyGrailQuest"/> //任务bean,具体任务为圣杯探险 <bean id="knight" class="com.springinaction.chapter01.knight.KnightOfTheRoundTable"> <constructor-arg value="Bedivere" /> <property name="quest" ref="quest" /> //将圣杯探险任务分配给圆桌骑士 </bean> |
public class KnightApp { public static void main(String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext( "com/springinaction/chapter01/knight/knight.xml"); Knight knight = (Knight) ctx.getBean("knight"); knight.embarkOnQuest(); } } |