spring依赖的maven dependency
http://mvnrepository.com/artifact/org.springframework
在pom.xml中添加如下依赖:
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.6.RELEASE</version> </dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.6.RELEASE</version> </dependency>
第一个例子:
首先设置一个接口Perofrmance表示参赛者。
package com.moonlit.myspring; public interface Performer { void perform() throws PerformanceException; }
创建一个Juggler(杂技师)类继承Performer表示参赛者是杂技师
package com.moonlit.myspring; public class Juggler implements Performer { private int beanBags = 3; public Juggler() { } public Juggler(int beanBags) { this.beanBags = beanBags; } public void perform() throws PerformanceException { System.out.println("JUGGLING " + beanBags + " BEANBAGS"); } }
在spring-idol.xml配置文件中定义一个名为duke的bean,他对应Juggler类(我把xml文件放在src/main/resources目录下)
<?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-3.0.xsd"> <bean id="duke" class="com.moonlit.myspring.Juggler" /> </beans>
测试代码:
package com.moonlit.practice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.moonlit.myspring.PerformanceException; import com.moonlit.myspring.Performer; public class FirstBean { public static void main(String[] args) throws PerformanceException { ApplicationContext context = new ClassPathXmlApplicationContext( "spring-idol.xml"); Performer performer = (Performer) context.getBean("duke"); performer.perform(); } }
运行结果如下:
JUGGLING 3 BEANBAGS
理解:首先定义了一个接口Performer,然后写了一个类Juggler继承自Peformer,Juggler有一个私有成员变量beanBags,他的默认值是3,然后Juggler实现了Performer的perform方法,方法的输出带有beanBags的数量。
然后在测试的程序中,通过ApplicationContext类型对象加载了spring-idol.xml文件的内容,而在xml文件中定义了名为"duke"的bean,然后我刚好就用到了。
然后bean返回的是一个Juggler,所以我将
Performer performer = (Performer) context.getBean("duke");
改成
Juggler performer = (Juggler) context.getBean("duke");
也是可以的,但是在这里我想看的效果是通过application context返回的是不是一个Juggler,因为通过输出的结果就可以知道了,所以我这里用(Performer),对中输出的效果显示bean对应的Performer真的是一个Juggler,这就是通过xml定义一个bean并通过application context获得这个bean对象的整个过程。
时间: 2024-10-14 04:43:27