With the increasing use of Springboot agile development, greater use of Spring annotation configuration, rather than applicationContext.xml file of Spring.
- Configuration Notes: Spring resolves to class configuration, the equivalent of spring profile
- Bean Note: Registration Bean container components, the default id is the method name
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
Equivalent to beans.xml file
<beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans>
1) applicationContext.xml file - Pack scan
@ComponentScans(value = {@ComponentScan(value = "com.self",excludeFilters = { @Filter(type = FilterType.ANNOTATION,classes = {Controller.class}) }) }) @Configuration public class RootConfig { //测试Bean @Bean public Person person() { return new Person("张励",22,"工程师"); } }
2) file import properties
@PropertySource(value = {"classpath:person.properties"}) @Configuration public class MainConfigOfProperty { @Bean public Person person() { return new Person(); } }
Assignment
the Person class {public @Value ( "PERSON.NAME $ {}") // profile property Private String name; }
3) Data source
@EnableTransactionManagement//开启基于注解的事务管理功能 @ComponentScan("com.self.ds") @Configuration public class TxConfig { //数据源 @Bean public DataSource dataSource() throws Exception{ ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("000111"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/self"); return dataSource; } @Bean public JdbcTemplate jdbcTemplate() throws Exception{ JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource()); return jdbcTemplate; } //事务管理器 @Bean public PlatformTransactionManager transactionManager() throws Exception{ return new DataSourceTransactionManager(dataSource()); } }
unit test
public class IOCTest { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); @Test public void test02() { Object bean1 = applicationContext.getBean("person"); Object bean2 = applicationContext.getBean("person"); System.out.println( bean1 == bean2); } @Test public void test01() { Object bean = applicationContext.getBean("person01"); System.out.println("结果: " + bean); } @Test public void test() { String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for(String beanDef:beanDefinitionNames) { System.out.println ( "Output:" + beanDef); } } }
Results of the