基础配置
  • 启用组件扫描配置
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”
GitHub地址:https://github.com/xc83415134/spring_bean_demo
环境: IDEA、Spring4.0
参考资料: 《spring实战》

转载于:https://www.cnblogs.com/njxc/p/8313388.html

spring使用之旅(一) ---- bean的装配相关推荐

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

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

  2. Spring学习之旅(一):Bean的基础装配

    Bean的基础装配有三种装配方法: 一:隐式Bean发现机制: Bean的发现机制基于组件扫描和自动装配两种机制. 组件扫描: 1.在要创建Bean的类上添加注解@Component,然后它生成的Be ...

  3. spring Bean自动装配

    spring Bean自动装配 自动装配是使用spring满足bean依赖的一种方式. spring会在应用上下文中为某个bean寻找其依赖的bean. spring自动装配需要从两个角度来实现,或者 ...

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

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

  5. Spring Boot2.x-04Spring Boot基础-使用注解装配bean

    文章目录 概述 通过Java配置文件@Bean的方式定义Bean 通过注解扫描的方式(@Component/@ComponentScan)装配Bean 使用excludeFilters属性不让IoC加 ...

  6. 【Spring实战4】04---装配Bean(自动装配)

    主要内容: 声明Bean 构造器注入和Setter方法注入 装配Bean 控制bean的创建和销毁 Spring装配Bean的3种机制 在XML中进行显式配置 在Java中进行显式配置 隐式的bean ...

  7. Spring Bean的装配(非XML文件方式)

    2019独角兽企业重金招聘Python工程师标准>>> Spring提供三种装配Bean的方法: 自动化装配Bean Java 代码中显式配置Bean XML配置文件配置Bean 自 ...

  8. Spring学习(七)bean装配详解之 【通过注解装配 Bean】【自动装配的歧义解决】...

    本文借鉴:Spring学习,@Bean 的用法(特此感谢!) 自动装配 1.歧义性 我们知道用@Autowired可以对bean进行注入(按照type注入),但如果有两个相同类型的bean在IOC容器 ...

  9. Spring学习(六)bean装配详解之 【通过注解装配 Bean】【基础配置方式】

    本文借鉴:Spring学习(特此感谢!) 通过注解装配 Bean 1.前言 优势 1.可以减少 XML 的配置,当配置项多的时候,XML配置过多会导致项目臃肿难以维护 2.功能更加强大,既能实现 XM ...

  10. Spring 框架基础(02):Bean的生命周期,作用域,装配总结

    本文源码:GitHub·点这里 || GitEE·点这里 一.装配方式 Bean的概念:Spring框架管理的应用程序中,由Spring容器负责创建,装配,设置属性,进而管理整个生命周期的对象,称为B ...

最新文章

  1. 祖传人像玩家,如何把AI秀出新高度
  2. 我理解的配置管理系统
  3. 循环首次适应算法_面向6G的极化编码链路自适应技术
  4. ubuntu设置代理 的三种方式
  5. 高晓松侃5G!2019开年大讲揭示运营商的秘密
  6. APICloud学习笔记之窗体跳转
  7. nagios监控linux主机及服务信息
  8. C++ 基类和派生类的virtual虚析构函数
  9. 2017.4.5 java中static关键字
  10. java自学百度网盘,绝对干货分享
  11. Nsight Compute内存访问常用Metrics含义理解
  12. idea快捷键,可摆脱鼠标
  13. 行业分类代码 2017 最新版 创建sql语句
  14. 设置字根,配合rem适配(多尺寸屏幕的适配)
  15. Android ANR日志分析指南
  16. 华为HCIA鲲鹏生态体系介绍
  17. Excel进销存专业版
  18. Java实现语音阅读功能开发(输入文字,转语音播放)
  19. 安卓系统怎么模拟java_电脑上安装安卓系统模拟器的方法(直接用JAVA虚拟成手机)...
  20. 水滴pin安卓版apk_小水滴app下载

热门文章

  1. redis映射的概念_Redis存储总是心里没底?你大概漏了这些数据结构原理
  2. amd自定义分辨率_Intel首款独显性能走光:AMD/NVIDIA芒刺在背
  3. java jexl_利用Jexl实现数据库的计算公式在Java中执行
  4. python21天打卡Day12--for循环,列表推导式-构建列表
  5. 21天 Jenkins打卡-Day1 环境准备
  6. Gatling性能测试(一)
  7. 超详细 | 接口自动化测试总结与分享入门篇
  8. linux 4433端口,linux – 使用相同的openssl端口443绑定不同端口的apache ssl端口
  9. (四)Linux 安装 jdk
  10. android 相机和照片一起_Android相机开发(三): 实现拍照录像和查看