Spring注解--实现applicationContext.xml效果

 随着越来越多地使用Springboot敏捷开发,更多地使用注解配置Spring,而不是Spring的applicationContext.xml文件。

  • Configuration注解: Spring解析为配置类,相当于spring配置文件
  • Bean注解:容器注册Bean组件,默认id为方法名
@Configuration
public class AppConfig {
     @Bean
     public MyService myService() {
        return new MyServiceImpl();
     }
}        

等同于beans.xml文件

<beans>
    <bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>

1)applicationContext.xml文件-包扫描

@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)导入properties文件

@PropertySource(value = {"classpath:person.properties"})
@Configuration
public class MainConfigOfProperty {

	@Bean
	public Person person() {
		return new Person();
	}
}

赋值

public class Person {

   @Value("${person.name}")//配置文件属性
	private String name;

}

3)数据源

@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());
	}
	

}

  

单元测试

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("输出: " + beanDef);
		}
		
	}

}

执行结果

  

  

转载于:https://www.cnblogs.com/walkwithmonth/p/11536486.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值