随着越来越多地使用Springboot敏捷开发,更多地使用注解配置Spring,而不是Spring的applicationContext.xml文件。
-
Configuration注解: Spring解析为配置类,相当于spring配置文件
-
Bean注解:容器注册Bean组件,默认id为方法名
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
等同于beans.xml文件
1<beans> 2 <bean id="myService" class="com.acme.services.MyServiceImpl"/> 3</beans>
1)applicationContext.xml文件-包扫描
1@ComponentScans(value = {@ComponentScan(value = "com.self",excludeFilters = { 2 @Filter(type = FilterType.ANNOTATION,classes = {Controller.class}) 3 }) 4}) 5@Configuration 6public class RootConfig { 7 8 //测试Bean 9 @Bean 10 public Person person() { 11 return new Person("张励",22,"工程师"); 12 } 13}
2)导入properties文件
1@PropertySource(value = {"classpath:person.properties"}) 2@Configuration 3public class MainConfigOfProperty { 4 5 @Bean 6 public Person person() { 7 return new Person(); 8 } 9}
赋值
1public class Person { 2 3 @Value("${person.name}")//配置文件属性 4 private String name; 5 6}
3)数据源
1@EnableTransactionManagement//开启基于注解的事务管理功能 2@ComponentScan("com.self.ds") 3@Configuration 4public class TxConfig { 5 6 //数据源 7 @Bean 8 public DataSource dataSource() throws Exception{ 9 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 10 dataSource.setUser("root"); 11 dataSource.setPassword("000111"); 12 dataSource.setDriverClass("com.mysql.jdbc.Driver"); 13 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/self"); 14 return dataSource; 15 } 16 17 18 @Bean 19 public JdbcTemplate jdbcTemplate() throws Exception{ 20 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource()); 21 return jdbcTemplate; 22 } 23 24 //事务管理器 25 @Bean 26 public PlatformTransactionManager transactionManager() throws Exception{ 27 return new DataSourceTransactionManager(dataSource()); 28 } 29 30 31}
单元测试
1public class IOCTest { 2 3 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); 4 5 @Test 6 public void test02() { 7 Object bean1 = applicationContext.getBean("person"); 8 Object bean2 = applicationContext.getBean("person"); 9 System.out.println( bean1 == bean2); 10 } 11 12 @Test 13 public void test01() { 14 Object bean = applicationContext.getBean("person01"); 15 System.out.println("结果: " + bean); 16 } 17 18 19 @Test 20 public void test() { 21 String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); 22 for(String beanDef:beanDefinitionNames) { 23 System.out.println("输出: " + beanDef); 24 } 25 26 } 27 28}
执行结果
