您好,登錄后才能下訂單哦!
小編給大家分享一下Spring注解如何實(shí)現(xiàn)applicationContext.xml效果,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
隨著越來越多地使用Springboot敏捷開發(fā),更多地使用注解配置Spring,而不是Spring的applicationContext.xml文件。
Configuration注解: Spring解析為配置類,相當(dāng)于spring配置文件
Bean注解:容器注冊Bean組件,默認(rèn)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)導(dǎo)入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)數(shù)據(jù)源
@EnableTransactionManagement//開啟基于注解的事務(wù)管理功能 @ComponentScan("com.self.ds") @Configuration public class TxConfig { //數(shù)據(jù)源 @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; } //事務(wù)管理器 @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("結(jié)果: " + bean); } @Test public void test() { String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for(String beanDef:beanDefinitionNames) { System.out.println("輸出: " + beanDef); } } }
執(zhí)行結(jié)果
以上是“Spring注解如何實(shí)現(xiàn)applicationContext.xml效果”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。