Spring新注解
@Configuration
指定当前类是一个配置类
@ComponentScan
用于通过注解指定Spring创建容器时需要扫描的包
@Bean
将当前方法的返回值作为bean对象存入IoC容器中
如下类,可代替xml配置文件
package com.oylong.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
@Configuration
@ComponentScan("com.oylong")
public class SpringConfig {
@Bean("queryRunner")
@Scope("prototype")
public QueryRunner creatQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean("dataSource")
public DataSource creatDateSource() {
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass("com.mysql.cj.jdbc.Driver");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
ds.setJdbcUrl("jdbc:mysql://192.168.3.66:3306/test");
ds.setUser("root");
ds.setPassword("123123");
return ds;
}
}
在获取容器时,使用如下方法:
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
@Import
用于倒入其他的配置类
@PropertySource
用于加载properties资源,配合
@Value
属性来使用- 关键字
classpath
表示类路径下
- 关键字