好久以前就想系统的学习和掌握Spring框架,可是拖了好久都没有行动。如今趁着在外出差琐事很少,就花时间来由浅入深的研究下Spring框架。Spring框架这几年来已经发展成为一个巨无霸产品。从最初的只是用来做为依赖注入到如今已是没法不包。其涉及的领域有依赖注入、MVC、JMS、Web flow、Batch job、Web service、Security…..几乎是涵盖了技术开发的全部方面。本人虽然从事Java语言开发时间不长,可是对Spring中的不少组件都有所涉猎,好比上面列出的那几个都有用过。能够说Spring是Java程序员必需要掌握的一个库。java
如今Spring的最新的稳定版本是4.0.2,该版本中包含了大量的新特性,是比较重要的一次release。本系列将基本使用该版本进行讲解。git
第一讲就用一个简单的例子开始吧,初步学会使用Spring-Context的依赖注入功能。程序员
首先使用maven建立一个新的项目。github
1
|
$: mvn archetype:generate |
建立成功后在pom.xml文件中加入对Spring-Context的依赖。spring
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.2.RELEASE</version> </dependency> </dependencies> |
而后咱们建立一个MovieService的接口。bash
1 2 3 4 5 6 |
package huangbowen.net.service; public interface MovieService { String getMovieName(); } |
建立一个DefaultMovieService来实现这个接口。app
1 2 3 4 5 6 7 8 |
package huangbowen.net.service; public class DefaultMovieService implements MovieService { public String getMovieName() { return "A Touch of Sin"; } } |
而后建立一个Cinema类,会使用MoviceService来放电影。框架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package huangbowen.net.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Cinema { @Autowired private MovieService movieService; public void printMovieName() { System.out.println(movieService.getMovieName()); } } |
创建一个Application类。maven
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package huangbowen.net; import huangbowen.net.service.Cinema; import huangbowen.net.service.DefaultMovieService; import huangbowen.net.service.MovieService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class Application { @Bean public MovieService getMovieService() { return new DefaultMovieService(); } public static void main( String[] args ) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class); Cinema cinema = applicationContext.getBean(Cinema.class); cinema.printMovieName(); } } |
Ok,运行main函数,获得控制台输出:函数
1
|
A Touch of Sin |
本例子中主要使用Annotation功能来实现对MoviceService的注入。咱们将Cinema.java的头部标注为@Component说明该类交由Spring托管。而Cinema.java中的属性MoviceService标注为@Autowired,则Spring在初始化Cinema类时会从Application Context中找到类型为MovieService的Bean,并赋值给Cinema。在Application.java中咱们声明了一个类型为MovieService的Bean。而且标注Application.java为@Configuration,这是告诉Spring在Application.java中定义了一个或多个@Bean方法,让Spring容器能够在运行时生成这些Bean。@ComponentScan则会让Spring容器自动扫描当前package下的标有@Component的class,这些class都将由Spring托管。
本例中的源码请在个人GitHub上自行下载。