Spring注解--实现l效果
随着越来越多地使⽤Springboot敏捷开发,更多地使⽤注解配置Spring,⽽不是Spring的l⽂件。
Configuration注解: Spring解析为配置类,相当于spring配置⽂件
Bean注解:容器注册Bean组件,默认id为⽅法名
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
等同于l⽂件
<beans>
<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>
1)l⽂件-包扫描
@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("sql.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 = Bean("person");
Object bean2 = Bean("person");
System.out.println( bean1 == bean2);
}
spring怎么读取xml文件@Test
public void test01() {
Object bean = Bean("person01");
System.out.println("结果: " + bean);
}
@Test
public void test() {
String[] beanDefinitionNames = BeanDefinitionNames();
for(String beanDef:beanDefinitionNames) {
System.out.println("输出: " + beanDef);
}
}
}
执⾏结果
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论