将 Spring 配置到应用开发中有以下三种方式:

  1. 基于xml配置:通常一开头
  2. 基于注解配置:@Controller @Service @Autowired @RequestMapping @RequestParam @ModelAttribute @Cacheable @CacheFlush @Resource @PostConstruct @PreDestroy @Repository @Scope @SessionAttributes @InitBinder @Required @Qualifier
  3. 基于java配置

配置方式

具体

基于xml配置

“< beans>”

基于注解

@Controller、@Service、@Autowired 、@RequestMapping 、@RequestParam 、@ModelAttribute 、@Cacheable 、@CacheFlush 、@Resource 、@PostConstruct、 @PreDestroy 、@Repository 、@Scope 、@SessionAttributes 、@InitBinder 、@Required 、@Qualifier

基于java

@Configuration、@Bean

如何用XML配置Spring

在 Spring 框架中,依赖和服务需要在专门的配置文件来实现,我常用的 XML 格式的配置文件。这 些配置文件的格式通常用开头,然后一系列的 bean 定义和专门的应用配置 选项组成。

SpringXML 配置的主要目的时候是使所有的 Spring 组件都可以用 xml 文件的形式来进行配置。这 意味着不会出现其他的 Spring 配置类型(比如声明的方式或基于 Java Class 的配置方式) Spring 的 XML 配置方式是使用被 Spring 命名空间的所支持的一系列的 XML 标签来实现的。 Spring 有以下主要的命名空间:context、beans、jdbc、tx、aop、mvc 和 aso。
如:

<beans>
         <!-- JSON Support -->
         <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
         <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonV iew"/>
         <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>     
</beans>

下面这个 web.xml 仅仅配置了 DispatcherServlet,这件最简单的配置便能满足应用程序配置运 行时组件的需求。

<web-app>
    <display-name>Archetype Created Web Application</display-name>         
	<servlet>             
		<servlet-name>spring</servlet-name>             
		<servletclass>org.springframework.web.servlet.DispatcherServlet</servletclass>             
		<load-on-startup>1</load-on-startup>         
		</servlet>     
    <servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>     
</web-app>

怎样用注解的方式配置 Spring?

Spring 在 2.5 版本以后开始支持用注解的方式来配置依赖注入。可以用注解的方式来替代 XML 方 式的 bean 描述,可以将 bean 描述转移到组件类的 内部,只需要在相关类上、方法上或者字段声 明上使用注解即可。注解注入将会被容器在 XML 注入之前被处理,所以后者会覆盖掉前者对于同一 个属性的处理结 果。
注解装配在 Spring 中是默认关闭的。所以需要在 Spring 文件中配置一下才能使用基于注解的装配 模式。如果你想要在你的应用程序中使用关于注解的方法的话,请参考如下的配置。

<beans>
        <context:annotation-config/>        
        <!-- bean definitions go here -->     
</beans>

在 context:annotation-config/标签配置完成以后,就可以用注解的方式在 Spring 中向属 性、方法和构造方法中自动装配变量。

下面是几种比较重要的注解类型:

  1. @Required:该注解应用于设值方法。
  2. @Autowired:该注解应用于有值设值方法、非设值方法、构造方法和变量。
  3. @Qualifier:该注解和@Autowired 注解搭配使用,用于消除特定 bean 自动装配的歧义。
  4. JSR-250 Annotations:Spring 支持基于 JSR-250 注解的以下注解,@Resource、 @PostConstruct 和 @PreDestroy。

如何用基于 Java 配置的方式配置 Spring?

Spring 对 Java 配置的支持是由@Configuration 注解和@Bean 注解来实现的。由@Bean 注解 的方法将会实例化、配置和初始化一个 新对象,这个对象将由 Spring 的 IoC 容器来管理。 @Bean 声明所起到的作用与 元素类似。被 @Configuration 所注解的类则表示这个类 的主要目的是作为 bean 定义的资源。被@Configuration 声明的类可以通过在同一个类的 内部调 用@bean 方法来设置嵌入 bean 的依赖关系。
最简单的@Configuration 声明类请参考下面的代码:

@Configuration     
public class AppConfig{
         @Bean         
         public MyService myService() {
                return new MyServiceImpl();
         }     
}

对于上面的@Beans 配置文件相同的 XML 配置文件如下:

<beans>         
		<bean id="myService" class="com.somnus.services.MyServiceImpl"/>     
</beans>

上述配置方式的实例化方式如下:利用 AnnotationConfigApplicationContext 类进行实例化

public static void main(String[] args) {
         ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);         
         MyService myService = ctx.getBean(MyService.class);         
         myService.doStuff();     
}

要使用组件组建扫描,仅需用@Configuration 进行注解即可:

@Configuration     
@ComponentScan(basePackages = "com.somnus")     
public class AppConfig  {         ...     }

在上面的例子中,com.acme 包首先会被扫到,然后再容器内查找被@Component 声明的类,找 到后将这些类按照 Sring bean 定义进行注册。
如果你要在你的 web 应用开发中选用上述的配置的方式的话,需要用 AnnotationConfigWebApplicationContext 类来读 取配置文件,可以用来配置 Spring 的 Servlet 监听器 ContextLoaderListener 或者 Spring MVC 的 DispatcherServlet。

<web-app>
         <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext -->         
         <context-param>
       		 <param-name>contextClass</param-name>             
             <param-value>
                     org.springframework.web.context.support.AnnotationConfigWebApplicatio nContext             
             </param-value>
         </context-param>
               <!-- Configuration locations must consist of one or more comma- or space-delimited             fully-qualified @Configuration classes. Fully-qualified packages may also be             specified for component-scanning -->
         <context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>com.howtodoinjava.AppConfig</param-value>
         </context-param>
               <!-- Bootstrap the root application context as usual using ContextLoaderListener -->    
    <listener>
             <listenerclass>org.springframework.web.context.ContextLoaderListener</listener -class>
         </listener>
               <!-- Declare a Spring MVC DispatcherServlet as usual -->
         <servlet>
             <servlet-name>dispatcher</servlet-name>
             <servletclass>org.springframework.web.servlet.DispatcherServlet</servletclass>
             <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext -->
             <init-param>
                 <param-name>contextClass</param-name>
                 <param-value>
                     org.springframework.web.context.support.AnnotationConfigWebApplicatio nContext
                 </param-value>
             </init-param>
             <!-- Again, config locations must consist of one or more comma- or space-delimited and fully-qualified @Configuration classes -->
             <init-param>
                 <param-name>contextConfigLocation</param-name>
                 <param-value>com.howtodoinjava.web.MvcConfig</paramvalue>
             </init-param>
         </servlet>
               <!-- map all requests for /app/* to the dispatcher servlet -->
         <servlet-mapping>
             <servlet-name>dispatcher</servlet-name>
             <url-pattern>/app/*</url-pattern>
         </servlet-mapping>     
</web-app