zoukankan      html  css  js  c++  java
  • spring学习---3

    1.装配进阶

    1)environment-specific bean

    @profile

    @Configuration
    public class DataSourceConfig {
    @Bean(destroyMethod="shutdown")
    @Profile("dev")
    public DataSource embeddedDataSource() {
    return new EmbeddedDatabaseBuilder()
    .setType(EmbeddedDatabaseType.H2)
    .addScript("classpath:schema.sql")
    .addScript("classpath:test-data.sql")
    .build();
    }
    @Bean
    @Profile("prod")
    public DataSource jndiDataSource() {
    JndiObjectFactoryBean jndiObjectFactoryBean =
    new JndiObjectFactoryBean();
    jndiObjectFactoryBean.setJndiName("jdbc/myDS");
    jndiObjectFactoryBean.setResourceRef(true);
    jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
    return (DataSource) jndiObjectFactoryBean.getObject();
    }
    }

    2)conditioinal beans

    @Conditional

    @Bean
    @Conditional(MagicExistsCondition.class)
    public MagicBean magicBean() {
    return new MagicBean();
    }

    3)ambiguity in autowiring

    autowiring works when exactly one bean matches the disired result.

    @ Primary--- designating a primary bean

    @Qualifier("beanid")

    4)Scoping beans

    在spring的应用上下文中,所有的bean都是单例的

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

     Singleton—One instance of the bean is created for the entire application.
     Prototype—One instance of the bean is created every time the bean is injected
    into or retrieved from the Spring application context.
     Session—In a web application, one instance of the bean is created for each session.
     Request—In a web application, one instance of the bean is created for each
    request.

    5)runtime value injection

    @Configuration
    @PropertySource("classpath:/com/soundsystem/app.properties")
    public class ExpressiveConfig {
    @Autowired
    Environment env;
    @Bean
    public BlankDisc disc() {
    return new BlankDisc(
    env.getProperty("disc.title"),
    env.getProperty("disc.artist"));
    }
    }

    6) wiring with Spring Expression Language(SpEL)

    #{}

  • 相关阅读:
    [Swift]LeetCode1249. 移除无效的括号 | Minimum Remove to Make Valid Parentheses
    [Swift]LeetCode1240. 铺瓷砖 | Tiling a Rectangle with the Fewest Squares
    一位资深程序员大牛给予Java初学者的学习路线建议
    Java基础——集合源码解析 List List 接口
    Java定时任务调度详解
    Java实现CORS跨域请求
    假如时光倒流,我会这么学习Java
    Java后端程序员1年工作经验总结
    20个高级Java面试题汇总
    JVM内幕:Java虚拟机详解
  • 原文地址:https://www.cnblogs.com/flyingbee6/p/5351414.html
Copyright © 2011-2022 走看看