使用bean注解配置mysql
时间: 2024-02-02 16:02:50 浏览: 81
使用bean注解配置mysql需要在Spring配置文件中添加以下内容:
1. 在配置文件中添加命名空间和约束:
```
xmlns="http://www.springframework.org/schema/beans"
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"
```
2. 配置数据源:
```
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/databaseName" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
```
其中,id为dataSource,class为DriverManagerDataSource,driverClassName为com.mysql.jdbc.Driver,url为数据库连接地址,username为数据库用户名,password为数据库密码。
3. 配置DBHome类:
```
@Component
public class DBHome {
@Autowired
private DataSource dataSource;
public void test(){
Connection conn=null;
try {
conn =dataSource.getConnection();
Statement s =conn.createStatement();
ResultSet res =s.executeQuery("select * from userTable");
while(res.next()){
System.out.println(res.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
其中,@Component注解表示这是一个组件类,@Autowired注解表示自动注入数据源。
4. 在配置文件中开启注解扫描:
```
<context:component-scan base-package="com.example" />
```
其中,base-package为DBHome类所在的包名。
阅读全文
相关推荐
















