javaConfig

2018-05-08  本文已影响0人  小李_a98e

java Config

@Configuration
在类上打上这一标签,表示这个类是配置类

@ComponentScan
相当于xml的<context:componentscan basepakage=>

@Bean
bean的定义,相当于xml的
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" /> 

@EnableWebMvc
相当于xml的<mvc:annotation-driven>

@ImportResource
相当于xml的 <import resource="applicationContext-cache.xml">

@PropertySource
spring 3.1开始引入,它是基于java config的注解,用于读取properties文件

@Profile
spring3.1开始引入,一般用于多环境配置,激活时可用@ActiveProfiles注解
@ActiveProfiles("dev")
    等同于xml配置
<beans profile="dev">
    <bean id="beanname" class="com.pz.demo.ProductRPC"/>
</beans>

完整的例子
    @Configuration
    public class Config {
        @Autowired
        private Environment env;
    
        @Bean("dataSource")
        public DataSource getDataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(env.getProperty("spring.datasource.url"));
            dataSource.setUsername(env.getProperty("spring.datasource.username"));
            dataSource.setPassword(env.getProperty("spring.datasource.password"));
            return dataSource;
        }
    
        @Bean
        public JdbcTemplate getJdbcTemplate(@Qualifier("dataSource") DataSource dataSource){
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
            return jdbcTemplate;
        }
    
    }
上一篇 下一篇

猜你喜欢

热点阅读