Spring之新注解
-
下面我们把xml用一个类来替换
//标志该类是Spring的核心配置类 @Configuration public class SpringConfiguration { }
思想就是用类来代替spring配置文件,用注解来代替标签
- 组件扫描可以用Component注解代替,里面的参数就是包的范围
//<context:component-scan base-package="com" />
@ComponentScan("com")
-
加载properties的配置文件可以用PropertySource代替
//<context:property-placeholder location="classpath:jdbc.properties" /> @PropertySource("class:jdbc.properties")
-
@Bena注解将当前方法的返回值以指定名称存储到Spring容器
这里我们把数据库的一些初始信息存入spring容器中,并取名dataSource
public DataSource getDataSource() throws SQLException,
PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/study");
dataSource.setUser("root");
dataSource.setPassword("");
return dataSource;
}
可以上面的set方法里面的参数都写死了,又耦合了,那我们能用spring表达式吗?
答案是不能的,因为spring表达式实在spring配置文件中使用的,而这里是api并不能使用,那么该怎么办呢?
我们可以使用注入的方式,把它们用@Value的方式注入到成员变量中,因为刚刚已经用@PropertySource Spring加载了properties文件,所以我们可以把STL把配置文件中的值注入到成员变量中。
@Value("${jdbc.Driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws SQLException, PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
- 如果我们Spring核心配置文件过大,我们就需要把它分开,像上面的数据源的配置等等,我们可以把它们放到不同的Spring配置类中
- 比如下面我们新建了一个DataSourceConfiguration配置类,把DataSource相关的都放里面
//<context:property-placeholder location="classpath:jdbc.properties" />
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.Driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws SQLException, PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
-
然后在核心配置文件用@Import注解导入
@Import(DataSourceConfiguration.class)
如果导入多个配置文件,这里的参数其实是个数组 -
因为我们用注解代替了spring的配置文件,所以不能再像下面一样这么写了
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
}