Spring实战-第3章 高级装配- 高飞网

第3章 高级装配

——高级装配

2017-12-26 15:48:44.0

1、环境与profile

    1、配置profile bean @Profile

        @Profile("dev")

    <beans profile='dev'>

            <jdbc:embedded-database id="dataSource">

                    <jdbc:script location="classpath:schema.sql"/>

                    <jdbc:script location="classpah:test-data.sql"/>

            <jdbc:embedded-database>

    </beans>

    <beans profile="qa">

            <bean id="dataSource"

             class='org.apache.commons.dbcp.BasicDataSource'

              destroy-method='close'

                p:url="jdbc:h2:tcp://dbserver/~/test"

                p:driverClassName="org.h2.Driver"

                p:username="sa"

                p:password="password"

                p:initialSize="20"

                p:maxActive="30"/>

            </beans>

    </beans>

    <beans profile="prod">

            <jee:jndi-lookup id="dataSource"

                                        jndi-name="jdbc/myDatabase"

                                         resource-ref="true"

                                         proxy-intcrface="javax.sql.DataSource"/>

    </beans>



    2、激活profile

        spring.profiles.active

        spring.profiles.default


        <context-param>

                <param-name>spring.profiles.default</param-name>

                <param-value>dev</param-value>

        </context-param>


2.条件化的bean

    @Conditional

    AnnotatedTypeMetadata

    public interface AnnotatedTypeMetadata{

        boolean isAnnotated(String annotationType);


        Map<String,Object> getAnnotationAttributes(String annotationType);


        Map<String ,Object> getAnnotationAttributes(String annotationType,boolean clearValueAsString);


        MultiValueMap<String,Object> getAllAnnotationAttributes(

            String annotationType

        );

        MultiValueMap<String ,Object> getAllAnnotationAttributes(String annotationType,boolean classValuesAssuring);

    }


3.标示首选的bean

        @Primary


4.限定自动装配的bean

        @Qualifier (@Autowired @Inject)


5.注入外部的值

@PropertySource注解和Environment

    @Configuration

    @PropertySource("classpath:/com/soundsystem/app.properties")

      public class ExperssiveConfig{

        @Autowired

        Environment env;

        @Bean

        public BlankDisc desc(){

                return new BlankDisc(

                        env.getProperty("disc.title"),

                         env.getProperty("disc.artist"));

                    

                };

           }

    }






2、

上一篇:第2章 装配Bean