本文是基于之前案例讲解的,详情请看这里
故不再做之前的详细介绍了。
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd">
<!-- 开启注解注入 -->
<context:annotation-config />
<!-- 开启扫描添加了Component、Repository、Service、Controller注解的包和子包 -->
<context:component-scan base-package="com"/>
<!-- 引入属性配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
测试类
package com.test.demo;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.bean.User;
import com.web.controller.UserController;
/**
* 案例测试类
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class DemoTest {
@Autowired
private UserController userController;
@Test
public void testQuery() {
List<User> users = userController.query();
for (User user : users) {
System.out.println(user);
}
}
}
测试结果:
UserDaoImpl........
十一月 07, 2019 5:56:47 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited//这是日志信息
UserServiceImpl........
UserController.........
User [id=1, name=黄飞鸿, age=18, birthday=2019-11-07]