配置阿里巴巴提供的数据库连接类,让Spring帮忙管理
java
<context:property-placeholder location="classpath:config.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${uname}"></property>
<property name="password" value="${upassword}"></property>
<property name="initialSize" value="${initialSize}"></property><!--初始化连接数量-->
<property name="maxActive" value="${maxActive}"></property><!--最大连接数量-->
<property name="maxWait" value="${maxWait}"></property><!--最大等待超时时间-->
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
JdbcTemplate是Spring对jdbc的封装,提供了对数据库操作的方法,里面还可以直接包含数据源对象。
java
@Data
@Repository
public class UserDao {
@Autowired
JdbcTemplate jdbcTemplate;
Integer id;
String name;
public void select(){
jdbcTemplate.update("insert into user(name)value (?)","aaa");
}
}
java
@Data
@Service("userService")
public class UserService {
@Resource
UserDao userDao;
public void select(){
userDao.select();
}
}
java
public class test {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");//读取配置文件
UserService userService=applicationContext.getBean("userService",UserService.class);
userService.select();
}
}