Spring 注解开发 -- Spring新注解(完全替换Spring配置文件 使用配置类)
Posted Z && Y
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 注解开发 -- Spring新注解(完全替换Spring配置文件 使用配置类)相关的知识,希望对你有一定的参考价值。
1. Spring新注解
使用 原始注解 还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
新注解 + 原始注解 就可以完全脱离配置文件开发
1.1 新注解介绍
1.2 使用新注解进行开发
1.2.1 新建数据库配置文件
创建数据源文件:
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_ex_three
jdbc.username=root
jdbc.password=317525
1.2.2 配置数据源类
DataSourceConfiguration.java
package com.itheima.cofig;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
//<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") //Spring会将当前方法的返回值以指定名称(dataSource)存储到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
1.2.3 配置Spring核心配置类
SpringCofiguration.java
package com.itheima.cofig;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//标志该类是Spring的核心配置类
@Configuration
//<context:component-scan base-package="com.itheima"/> 配置注解的组件扫描范围
@ComponentScan("com.itheima")
//<import resource=""/> 导入数据源配置文件 接收的是一个数组
@Import({DataSourceConfiguration.class})
public class SpringCofiguration {
}
1.2.4 开始测试
UserController.java
package com.itheima.web;
import com.itheima.cofig.SpringCofiguration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.sql.Connection;
import java.sql.SQLException;
public class UserController {
public static void main(String[] args) throws SQLException {
// SpringCofiguration是我们刚刚创建的Spring核心配置类
ApplicationContext app = new AnnotationConfigApplicationContext(SpringCofiguration.class);
// ComboPooledDataSource是C3p0数据源
ComboPooledDataSource bean = app.getBean(ComboPooledDataSource.class);
Connection connection = bean.getConnection();
System.out.println(connection);
connection.close();
}
}
运行结果:
以上是关于Spring 注解开发 -- Spring新注解(完全替换Spring配置文件 使用配置类)的主要内容,如果未能解决你的问题,请参考以下文章