基础配置
  • 启用组件扫描配置
                    Java类配置文件方式
package com.springapp.mvc.application;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
}
 注:此处@Configuration为声明该类为配置文件类,@ComponentScan为声明开启扫描功能,若未配置基础包属性,则默认扫描该配置类所在当前包,否则扫描基础包定义的包
xml文件配置
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.springapp.mvc"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • 手动装配bean
          在大部分情况下我们都是使用组件扫描的的方式来装载bean,但有时候在使用第三方框架时,需要指定某些配置类,这种情况下通过手动配置则更加合适
                    Java类装配方式
package com.springapp.mvc.application;
 
import com.springapp.mvc.easyBean.Braves;
import com.springapp.mvc.easyBean.Sword;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
    @Bean(name = "braves")
    public Braves braves() {
        return new Braves(sword());
    }
    @Bean
    public Braves braves1() {
        Braves braves = new Braves();
        braves.setSword(sword());
        return braves;
    }
    @Bean
    public Sword sword() {
        return new Sword();
    }
}
             注:此处首先声明配置文件类,再通过在方法上@Bean注解,则spring将知道该方法会返回一个bean且注册到spring上下文中。@Bean注解若配置name属性,则Bean的ID为该值,否则默认和方法名一样。braves( ) 和braves1( ) 方法分别实现了构造函数注入和set方式注入
                    xml文件配置方式
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.springapp.mvc"/>
 
    <bean class="com.springapp.mvc.easyBean.Sword" id="sword"></bean>
    <bean class="com.springapp.mvc.easyBean.Braves" id="braves">
        <constructor-arg ref="sword"></constructor-arg>
    </bean>
    <bean class="com.springapp.mvc.easyBean.Braves" id="braves1">
        <property name="sword" ref="sword"></property>
    </bean>
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
               braves bean 和 braves1 bean分别实现了构造函数注入和set方式注入.
  • Java类和xml文件混合配置(单或多)
                   Java类配置
package com.springapp.mvc.application;
 
import com.springapp.mvc.easyBean.Sword;
import org.springframework.context.annotation.*;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
@Import(Application1.class)
@ImportResource("classpath:mvc-dispatcher-servlet.xml")
public class Application {
    @Bean
    public Sword sword() {
        return new Sword();
    }
}
注:此处@Import 注解为导入配置java类,@ImportResource注解为导入配置xml文件,此处可配置多个,通过都好隔开
                  xml文件配置
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.springapp.mvc"/>
 
    <import resource="mvc-dispatcher-servlet1.xml"></import>
    <bean class="com.springapp.mvc.application.Application"></bean>
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
 
     条件配置
  • spring profile 实现跨环境配置
                    1.配置profile bean
               java类配置
package com.springapp.mvc.application;
 
import ...
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
    @Bean
    public Braves braves(IArms arms){
        return new Braves(arms);
    }
    @Bean
    @Profile("dev")
    public Sword sword() {
        return new Sword();
    }
    @Bean
    @Profile("test")
    public Machete machete(){
        return new Machete();
    }
}
              注:通过@Profile注解声明该bean属于哪种环境下的(常见于数据库连接操作)
               xml文件配置
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.springapp.mvc"/>
 
    <beans profile="dev">
        <bean class="com.springapp.mvc.easyBean.Sword"></bean>
    </beans>
    <beans profile="test">
        <bean class="com.springapp.mvc.easyBean.Machete"></bean>
    </beans>
 
    <beans>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
</beans>
                    2.激活spring profile
<web-app version="2.4"
   xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
   <display-name>Spring MVC Application</display-name>
 
   <context-param>
      <param-name>spring.profiles.default</param-name>
      <param-value>dev</param-value>
   </context-param>
    <servlet>
      <servlet-name>mvc-dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>spring.profiles.default</param-name>
         <param-value>dev</param-value>
      </init-param>
        <load-on-startup>1</load-on-startup>
   </servlet>
 
   <servlet-mapping>
      <servlet-name>mvc-dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
               注:在web应用中,只需配置spring.profiles.default 或 spring.profiles.active,前者为默认后者为激活
                    3.测试一下
               在配置“dev”的情况下,只会有sword bean存在,使用machete bean则会报类不存在异常!
  • condition实现条件注册bean
                    定义一个实现condition接口的类,实现matches( )方法,在方法里面做校验判断
package com.springapp.mvc.application;
 
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
 
/**
 * Created by xuc on 2018/1/7.
 * 条件判断bean是否创建
 */
public class AppCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        if (environment.acceptsProfiles("dev") || environment.acceptsProfiles("test")){
            return true;
        }
        return false;
    }
}
                    注:@profile注解value校验就是通过condition实现的,ProfileCondition为其实现类如下:
 
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {
 
   /**
    * The set of profiles for which the annotated component should be registered.
    */
   String[] value();
 
}
 
class ProfileCondition implements Condition {
 
   @Override
   public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
      if (context.getEnvironment() != null) {
         MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
         if (attrs != null) {
            for (Object value : attrs.get("value")) {
               if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
                  return true;
               }
            }
            return false;
         }
      }
      return true;
   }
 
}
  • bean注入歧义性问题
                    1.在待注入bean上加@Primary注解,声明该bean为优先注入
package com.springapp.mvc.application;
 
import com.springapp.mvc.easyBean.Braves;
import com.springapp.mvc.easyBean.IArms;
import com.springapp.mvc.easyBean.Machete;
import com.springapp.mvc.easyBean.Sword;
import org.springframework.context.annotation.*;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
    @Bean
    @Conditional(AppCondition.class)
    public Braves braves(IArms arms){
        return new Braves(arms);
    }
    @Bean
    @Profile("dev")
    @Primary
    public Sword sword() {
        return new Sword();
    }
    @Bean
    @Profile("test")
    public Machete machete(){
        return new Machete();
    }
}
                   
                    2.在被注入bean上加@Qualifier注解
package com.springapp.mvc.application;
 
import com.springapp.mvc.easyBean.Braves;
import com.springapp.mvc.easyBean.IArms;
import com.springapp.mvc.easyBean.Machete;
import com.springapp.mvc.easyBean.Sword;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
    @Bean
    @Qualifier("sword")
    public Braves braves(IArms arms){
        return new Braves(arms);
    }
    @Bean
    @Profile("dev")
    public Sword sword() {
        return new Sword();
    }
    @Bean
    @Profile("test")
    public Machete machete(){
        return new Machete();
    }
}
                    注:此处若存在多个(即多优先级),可自定义注解
  • bean的作用域
 
作用域 描述
singleton 该作用域将 bean 的定义的限制在每一个 Spring IoC 容器中的一个单一实例(默认)。
prototype 该作用域将单一 bean 的定义限制在任意数量的对象实例。
request 该作用域将 bean 的定义限制为 HTTP 请求。只在 web-aware Spring ApplicationContext 的上下文中有效。
session 该作用域将 bean 的定义限制为 HTTP 会话。 只在web-aware Spring ApplicationContext的上下文中有效。
global-session 该作用域将 bean 的定义限制为全局 HTTP 会话。只在 web-aware Spring ApplicationContext 的上下文中有效。
 
package com.springapp.mvc.application;
 
import com.springapp.mvc.easyBean.Braves;
import com.springapp.mvc.easyBean.IArms;
import com.springapp.mvc.easyBean.Machete;
import com.springapp.mvc.easyBean.Sword;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
import org.springframework.web.context.WebApplicationContext;
 
/**
 * Created by xuc on 2018/1/7.
 * 配置类
 */
@ComponentScan(basePackages = {"com.springapp.mvc"})
@Configuration
public class Application {
    @Bean
    public Braves braves(IArms arms){
        return new Braves(arms);
    }
    @Bean
    @Profile("dev")
    @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION,
            proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Sword sword() {
        return new Sword();
    }
    @Bean
    @Profile("test")
    public Machete machete(){
        return new Machete();
    }
}
               注:此处通过@Scope注解重新定义sword bean为会话级作用域,由于在使用braves时会优先加载sword,通过proxyMode声明代理该类,
          即通过延迟注入的形式实现session级的sword注入到单例级的braves。如果该是接口的话:“proxyMode = ScopedProxyMode.INTERFACES”
 
 
 
环境: IDEA、Spring4.0
参考资料: 《spring实战》
 
 
 
 
 
 
 
 
 
 
 

spring使用之旅(一) ---- bean的装配的更多相关文章

  1. Spring XML配置里的Bean自动装配

    Spring自动装配 这段是我们之前编写的代码,代码中我们使用了P命名空间 并且使用手动装配的方式将car <bean id="address" class="cn ...

  2. Spring框架第二篇之Bean的装配

    一.默认装配方式 代码通过getBean();方式从容器中获取指定的Bean实例,容器首先会调用Bean类的无参构造器,创建空值的实例对象. 举例: 首先我在applicationContext.xm ...

  3. 《Spring实战》系列之Bean的装配-Days02

    2.1 回顾 对于我第一天在bean的装配中写的,是一些基本的语法或者是Spring本身的一些规定,但是我没有对此进行深究.接下来就让我们仔细的讨论一下细节问题.和传统的类的定义和方法的调用做一些比较 ...

  4. 《Spring实战》系列之Bean的装配-Days01

    1 自动化装配bean Spring通过两个方面实现对bean的自动装配 1 ) 组件扫描(component scaning):Spring会自动发现Spring上下文中的bean 2 ) 自动装配 ...

  5. 【Spring】Spring中的Bean - 5、Bean的装配方式(XML、注解(Annotation)、自动装配)

    Bean的装配方式 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 文章目录 Bean的装配方式 基于XML的装配 基于注解 ...

  6. Bean的装配方式

    (一) 知识点:Spring容器支持多种形式的Bean的装配方式,比如基于XML的装配,基于注解的装配和自动装配(最常用的就是基于注解的装配) Spring提供了两种基于xml的装配方式:设值注入(S ...

  7. Spring bean依赖注入、bean的装配及相关注解

    依赖注入 Spring主要提供以下两种方法用于依赖注入 基于属性Setter方法注入 基于构造方法注入 Setter方法注入 例子: public class Communication { priv ...

  8. Spring学习记录(三)---bean自动装配autowire

    Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系,少写几个ref autowire: no ---默认情况,不自动装配,通过ref手动引用 byName---根据 ...

  9. Spring学习系列(三) 通过Java代码装配Bean

    上面梳理了通过注解来隐式的完成了组件的扫描和自动装配,下面来学习下如何通过显式的配置的装配bean 二.通过Java类装配bean 在前面定义了HelloWorldConfig类,并使用@Compon ...

  10. 2015年11月30日 spring初级知识讲解(一)装配Bean

    序,Spring的依赖注入是学习spring的基础.IOC为控制反转,意思是需要的时候就由spring生成一个,而不是先生成再使用. 写在前面 Spring提供面向接口编程,面向接口编程与依赖注入协作 ...

随机推荐

  1. 【java设计模式】【行为模式Behavioral Pattern】策略模式Strategy Pattern

    package com.tn.策略模式; public class Client { private Strategy strategy; public void setStrategy(Strate ...

  2. NSQ之粗读浅谈

    回顾: 以前一直是C++开发(客户端),最近听同事讲go语言不错,随后便决定先从go语法开始投向go的怀抱.由于历史原因学习go语法时,用了半天的时间看完了菜鸟教程上相关资料,后来又看了易百教程上的一 ...

  3. MongoDB学习第七篇 --- sql和mongodb对比

    一.术语和概念的对比 SQL MongoDB database database     row document or BSON document column field index index ...

  4. android的ADK下载地址

    把下面所有的包下载到temp目录下进行安装. 用代理http://ppdaili.com/https://dl-ssl.google.com/android/repository/repository ...

  5. Java 并发编程:volatile的使用及其原理

    Java并发编程系列: Java 并发编程:核心理论 Java并发编程:Synchronized及其实现原理 Java并发编程:Synchronized底层优化(轻量级锁.偏向锁) Java 并发编程 ...

  6. thinkphp 中的钩子应用

    1 创建钩子行为: 我们自己定义的标签位可以直接放在Think\Behaviors中,也可以放在应用目录中,比如说Home模块下,新建一个Behaviors的文件夹,在文件夹内新建 标签名+Behav ...

  7. python中星号的意义(**字典,*列表或元组)

    传递实参和定义形参(所谓实参就是调用函数时传入的参数,形参则是定义函数是定义的参数)的时候,你还可以使用两个特殊的语法:*.** . 调用函数时使用* ,** test(*args)中 * 的作用:其 ...

  8. Java并发之底层实现原理学习笔记

    本篇博文将介绍java并发底层的实现原理,我们知道java实现的并发操作最后肯定是由我们的CPU完成的,中间经历了将java源码编译成.class文件,然后进行加载,然后虚拟机执行引擎进行执行,解释为 ...

  9. 动态求区间K大值(权值线段树)

    我们知道我们可以通过主席树来维护静态区间第K大值.我们又知道主席树满足可加性,所以我们可以用树状数组来维护主席树,树状数组的每一个节点都可以开一颗主席树,然后一起做. 我们注意到树状数组的每一棵树都和 ...

  10. SQL Server Service Broker创建单个数据库会话

    概述 SQL Server Service Broker 用来创建用于交换消息的会话.消息在目标和发起方这两个端点之间进行交换.消息用于传输数据和触发消息收到时的处理过程.目标和发起方既可以在同一数据 ...