第一步
导入jar包
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
第二步
书写核心配置文件beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<context:annotation-config/>
<!--组件扫描-->
<context:component-scan base-package="com.xszx"></context:component-scan>
</beans>
第三步
在beans.xml中配置数据源
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///sjt2405"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
第四步
使用数据库连接池实现原生的jdbc添加用户
@Repository
public class UserDaoImpl implements UserDao{
@Resource(name="dataSource")
private DataSource dataSource;
@Override
public void add(User user) {
try {
Connection connection = dataSource.getConnection();
String sql = "insert into user values(null,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,user.getName());
preparedStatement.setString(2,user.getPwd());
preparedStatement.setInt(3,user.getRole());
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
第五步
测试
//测试层
public class test {
public static void main(String[] args) throws Exception {
//读取核心配置文件
BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");
//获取bean(注解)
UserController userController =(UserController) beanFactory.getBean("userController");
//执行
userController.addUser();
}
}
//controller层
@Controller //controller控制反转的个性化注解,通用的是@Component
public class UserController {
User user = new User();
UserService userServiceImpl;
@Resource
public void setUserServiceImpl(UserService userServiceImpl) {
this.userServiceImpl = userServiceImpl;
}
public void addUser() throws Exception {
user.setRole(1);
user.setName("DBCP");
user.setPwd("123");
//执行
userService.addUser(user);
}
}