栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring 高级装配

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring 高级装配

spring 高级装配
  • 一、环境与profile
    • 1、java配置profile
    • 2、xml中配置profile
  • 二、激活profile
    • 1、激活方式有如下几种:
    • 2、读取方式和顺序
  • 三、条件化bean @Condition注解
    • 1、@Condition注解的作用
    • 2、Condition 接口使用
    • 3、@Profile注解源码
  • 四、运行时值注入
    • 1、属性占位符 ${..}
      • ①传统xml脚本配置
      • ② 或者配合自动装配和组件扫描,配合@Value注解
    • 2、spring表达式语言 #{..}


一、环境与profile 1、java配置profile
public interface DateSourceInterFace {//下面两个实现的接口
    public void printInfo();
}
@Component
@Profile("dev")
public class DevDateSour implements DateSourceInterFace{
    @Override
    public void printInfo() {
        System.out.println("this DEV profile.......");
    }
}
@Component
@Profile("pro")
public class ProDateSour implements DateSourceInterFace{
    @Override
    public void printInfo() {
        System.out.println("this Pro profile.......");
    }
}
@ComponentScan//spring扫描到spring容器中创建bean对象
@Configuration
public class ProfileConfig {

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ProfileConfig.class)
@ActiveProfiles("pro")//当前激活pro环境
public class ProfileTest {
    @Autowired
    private DateSourceInterFace dateSource;
    
    @Test
    public void test01(){
      dateSource.printInfo();
    }
}

结果:

this Pro profile.......
2、xml中配置profile

一个xml对象相当于一个配置类;如下有两种方式一种是分别两个xml表示两个环境,第二种是一个xml里面配置两个并设置profile属性,如下就是第二种演示。


    
    

    
    
        
    
    
        
    

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/profileContext.xml"})
@ActiveProfiles("pro")
public class ProfileXmlTest {
    @Autowired
    private DateSourceInterFace dateSource;

    @Test
    public void test01(){
        dateSource.printInfo();
    }
}
二、激活profile 1、激活方式有如下几种:
1、作为DispatcherServlet的初始化参数
2、作为web应用的上下文参数
3、作为环境变量
4、使用@ActiveProfiles激活

下面是web.xml中配置



    spring.profiles.default
    dev




  dispatcher
  org.springframework.web.servlet.DispatcherServlet
    
        spring.profiles.active
        pro
    



-Dspring.profiles.active="pro"
2、读取方式和顺序

①如果同时设置了 spring.profile.active=dev 和 spring.profile.default=pro ,只激活dev配置。
②如果没有配置spring.profile.active,只配置了spring.profile.default,才会读取default配置。
③那些没有定义在profile中的bean,任何时候都创建。

三、条件化bean @Condition注解 1、@Condition注解的作用

@Condition注解的bean,只有满足实现 Condition 接口的 matches 方法才创建,否则忽略。

@Configuration
public class MagicConfig {
  @Bean
  //MagicExistsCondition类中match方法返回true就穿件如下bean
  @Conditional(MagicExistsCondition.class)
  public MagicBean magicBean() {
    return new MagicBean();
  }  
}
public class MagicExistsCondition implements Condition {
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Environment env = context.getEnvironment();
    return env.containsProperty("magic");
  }  
}
2、Condition 接口使用

Condition 接口的matches方法的两个参数

public interface ConditionContext {
//可以检查bean定义
    BeanDefinitionRegistry getRegistry();
//检查bean是否存在,检查bean属性    
    ConfigurableListableBeanFactory getBeanFactory();
//获取环境中存在或者值时多少    
    Environment getEnvironment();
//获取resourceLoader加载的资源 
    ResourceLoader getResourceLoader();
//返回累加器,并检查类是否存在       
    ClassLoader getClassLoader();
}

AnnotatedTypeMetadata 可以检查@bean注解的方法上的其他注解信息。

public interface AnnotatedTypeMetadata {
//
	boolean isAnnotated(String annotationName);
	Map getAnnotationAttributes(String annotationName);
	Map getAnnotationAttributes(String annotationName, boolean classValuesAsString);
	MultiValueMap getAllAnnotationAttributes(String annotationName);
	MultiValueMap getAllAnnotationAttributes(String annotationName, boolean classValuesAsString);
}
3、@Profile注解源码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {
	
	String[] value();
}
class ProfileCondition implements Condition {

	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		if (context.getEnvironment() != null) {
	//获取@Profile注解的属性value值
			MultiValueMap attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
			if (attrs != null) {
				for (Object value : attrs.get("value")) {
				//从环境中检查是否含有该vlaue值,有则激活该环境,并创建该bean对象
					if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
						return true;
					}
				}
				return false;
			}
		}
		return true;
	}
}
四、运行时值注入 1、属性占位符 ${…} ①传统xml脚本配置
public class Food {
    private String eatFood;
    public void setEatFood(String eatFood) {
        this.eatFood = eatFood;
    }
    @Override
    public String toString() {
        return "Food{" + "eatFood='" + eatFood + ''' +'}';
    }
}



    
        
        
    

    
    

classpath:/part03/runTime.properties配置属性文件

food.eatFood=午餐必须带饭

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
//读取xml配置类
@ContextConfiguration(locations = {"classpath:/part03/runTimeConfig.xml"})
//可以通过如下注解读取配置文件
@PropertySource(value = {"classpath:/part03/runTime.properties"})
public class RuntTimeTest {
    @Autowired
    private Food food;

    @Test
    public void test01(){
        System.out.println(food.toString());
    }    
}

结果: Food{eatFood=‘午餐必须带饭’}

② 或者配合自动装配和组件扫描,配合@Value注解

@Value 和 @Autowired 相似用法,创建bean时自动注入值

@Component
public class Food {
    private String eatFood;
    
    public void setEatFood(@Value("${food.eatFood}") String eatFood) {
        this.eatFood = eatFood;
    }
    @Override
    public String toString() {
        return "Food{" + "eatFood='" + eatFood + ''' +'}';
    }
2、spring表达式语言 #{…}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020123.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号