配置类 · 注解@Value ·以及如何引用其他的 ioc 组件
// TODO:创建 java的配置类 取代xml配置文件
@Configuration //配置类注解
@ComponentScan(basePackages = {"com.wind.dao", "com.wind.service"}) // 包扫描注解配置 可存入多个包
@PropertySource(value = "classpath:jdbc.properties") //引用外部文件 注解 value可省略
public class JavaConfiguration {
/*
情况1: ${key} 取外部配置key对应的值
情况2: ${key:defaultValue} 没有key,可以给与默认值 @Value("${wind.username:hahaha}") */
@Value("${wind.url}") //设置默认值
private String url;
@Value("${wind.drive}")
private String drive;
@Value("${wind.username}")
private String username;
@Value("${wind.password}")
private String password;
@Bean // TODO:将配置类的方法创建的组件存储到ioc容器 ( <bean> --> 一个方法 )
//方法的返回值类型:bean组件的类型 或他的父类 或接口
//方法名字: bean id
public DruidDataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(drive);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean //对于形式参数,还可以 用注入的方式 设置属性值
public DruidDataSource dataSource1(@Value("${wind.url}") String url, @Value("${wind.driver}") String drive,
@Value("${wind.username}") String username,
@Value("${wind.password}") String password) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(drive);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
/**
* 1.beanName的问题
* 默认方法名
* 指定 name/value 属性起名字 覆盖方法名
*
* @Bean(name = "jdbc") 可以为方法重命名 覆盖原有方法名
* 2.周期方法如何指定
* bean属性指定 --> @Bean(initMethod = "",destroyMethod = "")
* 3.作用域 和之前一样使用 @Scope注解 默认单例
* @Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
* 4.如何引用其他的 ioc 组件
* 4.1直接调用对方的 bean方法 (不推荐)
* 4.2直接形参变量进行引入,要求必须有对应的组件,如果有多个, 形参名=组件id标识 或者设置的 name 名
*/
@Bean
public JdbcTemplate jdbcTemplate1() {
//需要DateSource 需要ioc容器的其他组件
//方案1 如果其他组件也是 @Bean方法 可以直接调用 | 从ioc容器直接获取
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
@Bean
public JdbcTemplate jdbcTemplate2(DataSource dataSource) { //如果 方法是重命名的 则 DataSource jdbc
//需要DateSource 需要ioc容器的其他组件
//方案2 形参列表声明想要的组件类型 可以是一个或多个 (ioc 容器注入)
// 形参注入 :必须要有对应的类型的组件
// 如果没有:抛异常
// 如果有多个: 使用形参名称等同于对应的bean id标识即可
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
}
点我查看结果
public class ReplaceXml {
@Test
public void test() {
//方式1:创建ioc容器
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(JavaConfiguration.class);
//方式2:创建ioc容器
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(JavaConfiguration.class);
annotationConfigApplicationContext.refresh();
// 获取组件
UserService bean = applicationContext.getBean(UserService.class);
System.out.println(bean);
}
}
![]()