好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java Spring详解如何配置数据源注解开发以及整合Junit

Spring数据源的配置

数据源(连接池)的作用

数据源(连接池)是提高程序性能如出现的
事先实例化数据源,初始化部分连接资源
使用连接资源时从数据源中获取
使用完毕后将连接资源归还给数据源

常见的数据源(连接池):DBCP、C3PO、BoneCP、Druid等

数据源的开发步骤

1、导入数据源的坐标和数据库驱动坐标
2、创建数据源对象
3、设置数据源的基本连接数据
4、使用数据源获取连接资源和归还连接资源

手动创建数据源

1、导入c3p0和druid坐标,mysql数据库驱动坐标

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

< dependency >

   < groupId >c3p0</ groupId >

   < artifactId >c3p0</ artifactId >

   < version >0.9.1.2</ version >

</ dependency >

< dependency >

   < groupId >com.alibaba</ groupId >

   < artifactId >druid</ artifactId >

   < version >1.1.10</ version >

</ dependency >

< dependency >

   < groupId >mysql</ groupId >

   < artifactId >mysql-connector-java</ artifactId >

   < version >5.1.32</ version >

</ dependency >

2、创建C3P0连接池

?

1

2

3

4

5

6

7

8

9

10

11

12

Test

public void testC3P0 ( ) throws Exception {

//创建数据源

ComboPooledDataSource dataSource = new ComboPooledDataSource () ;

//设置数据库连接参数

dataSource.setDriverClass ( "com.mysql.jdbc.Driver" ) ;

dataSource.setJdbcUrl ( "jdbc:mysql ://localhost:3306/test" ) ;

datasource.setUser ( "root" );

dataSource.setPassword ( "root" );

//获得连接对象

Connection connection = dataSource.getConnection ();

system.out.println (connection) ;

创建Druid连接池

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@Test

public void testDruid ( ) throws Exception {

//创建数据源

DruidDataSource dataSource = new DruidDatasource () ;

//设置数据库连接参数

dataSource.setDriverclassName ( "com.mysql.jdbc .Driver" ) ;

datasource.setUrl ( "jdbc:mysql : //localhost:3306/test" ) ;

datasource.setUsername ( "root" ) ;

datasource.setPassword ( "root" ) ;

//获得连接对象

connection connection = dataSource.getConnection ( ) ;

System.out.println (connection) ;

)

3、提取jdbc.properties配置文件

?

1

2

3

4

jdbc .driver=com.mysql.jdbc.Driver

jdbc.url=jdbc :mysql://localhost:3306/test

jdbc.username=root

jdbc. password =root

4、读取jdbc.properties配置文件创建连接池

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@Test

//测试手动创建 c3p0 数据源(加载properties配置文件)

public void test3() throws Exception {

     //读取配置文件

     ResourceBundle rb = ResourceBundle.getBundle( "jdbc" );

     String driver = rb.getString( "jdbc.driver" );

     String url = rb.getString( "jdbc.url" );

     String username = rb.getString( "jdbc.username" );

     String password = rb.getString( "jdbc.password" );

     //创建数据源对象  设置连接参数

     ComboPooledDataSource dataSource = new ComboPooledDataSource();

     dataSource.setDriverClass(driver);

     dataSource.setJdbcUrl(url);

     dataSource.setUser(username);

     dataSource.setPassword(password);

 

     Connection connection = dataSource.getConnection();

     System.out.println(connection);

     connection.close();

 

}

Spring配置数据源

可以将DataSource的创建权交由Spring容器去完成
DataSource有无参构造方法,而Spring默认就是通过无参构造方法实例化对象的
DataSource要想使用需要通过set方法设置数据库连接信息,而Spring可以通过set方法进行字符串注入

?

1

2

3

4

5

6

< bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" >

     < property name = "driverClass" value = "com.mysql.jdbc.Driver" />

     < property name = "jdbcUrl" value = "jdbc:mysql://localhost:3306/test" />

     < property name = "user" value = "root" />

     < property name = "password" value = " root" />

</ bean >

测试从容器当中获取数据源

?

1

2

3

4

5

ApplicationContext applicationContext = new ClassPathXmlApplicationContext ( "applicationContext.xml" ) ;

DataSource dataSource = ( DataSource)

applicationcontext. getBean ( "dataSource" ) ;

Connection connection = dataSource.getConnection ( ) ;

System.out.println ( connection) ;

抽取jdbc配置文件

applicationContext.xml加载jdbc.properties配置文件获得连接信息。
首先,需要引入context命名空间和约束路径:
命名空间: xmIns:context="http://HdhCmsTestspringframework.org/schema/context"

约束路径: http://HdhCmsTestspringframework.org/schema/context
http://HdhCmsTestspringframework.org/schema/context/spring-context.xsd

?

1

2

3

4

5

6

7

< context:property-placeholder location = " classpath:jdbc.properties" />

< bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" >

     < property name = "driverclass" value = "${jdbc.driver}" />

     < property name = "jdbcUrl" value = "${jdbc.url}" />

     < property name = "user" value = "${jdbc.username} " />

     < property name = "password" value = "${jdbc.password}" />

</ bean >

Spring容器加载properties文件

?

1

2

< context:property-placeholder location = "xx.properties" />

< property name = " " value = "${key} " />

Spring注解开发

Spring原始注解

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置
文件可以简化配置,提高开发效率。

Spring原始注解主要是替代<Bean>的配置

注意:
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。

?

1

2

<!--注解的组件扫描-->

< context:component-scan base-package = "com.longdi " ></ context: component-scan>

使用@Compont或@Repository标识UserDaolmpl需要Spring进行实例化。

?

1

2

3

4

5

6

7

/ / @Component ( "userDao" )

@Repository ( "userDao" )

public class UserDaoImpl implements UserDao {

@override

public void save ( ) {

system.out.println ( "save running . . . ..." ) ;

}

使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入

?

1

2

3

4

5

6

7

8

9

10

11

12

// @Component ( "userservice ")

@service ( "userservice" )

public class UserserviceImpl implements UserService {

/*@Autowired

CQualifier ( "userDao")*/

     @Resource (name= "userDao" )

     private UserDao userDao;

     @override

     public void save ( ) {

     userDao.save ( ) ;

}

)

使用@Value进行字符串的注入

?

1

2

3

4

5

6

7

8

9

10

11

12

@Repository ( "userDao" )

public class UserDaoImpl implements UserDao {

@value ( "注入普通数据" )

private string str;

@value ( "${jdbc.driver} " )

private string driver;

@override

public void save () {

system.out.println (str) ;

system.out.println (driver) ;

system.out.println ( "save running......" ) ;

)

使用@Scope标注Bean的范围

?

1

2

3

4

5

//  @scope ( "prototype ")

     @Scope ( "singleton" )

public class UserDaoImpl implements UserDao {

//此处省略代码

)

使用@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法

?

1

2

3

4

5

6

7

8

@PostConstruct

public void init () {

system.out.println ( "初始化方法...." );

}

@PreDestroy

public void destroy () {

system.out.println ( "销毁方法....." );

)

Spring新注解

使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
非自定义的Bean的配置: <bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置: <context:component-scan>
引入其他文件:<import>

@Configuration

@ComponentScan

@lmport

?

1

2

3

4

5

6

@Configuration

@componentScan ( "com.longdi" )

@Import ({DataSourceConfiguration. class })

public class SpringConfiguration {

 

)

@PropertySource

@value

?

1

2

3

4

5

6

7

8

9

10

@Propertysource ( "classpath:jdbc.properties" )

public class DataSourceConfiguration {

@value ( "${jdbc.driver}" )

private string driver ;

@value ( "${jdbc.ur1 }" )

private string url;

@value ( "${jdbc.username}" )

private string username ;

@value ( "${jdbc.password]" )

private string password;

@Bean

?

1

2

3

4

5

6

7

8

Bean (name= "dataSource " )

public DataSource getDataSource () throws PropertyvetoException {

ComboPooledDataSource dataSource = new ComboPooledDataSource ( ) ;

datasource.setDriverclass (driver) ;

datasource.setJdbcUrl (url) ;

datasource.setUser (username ) ;

dataSource.setPassword(password) ;

return dataSource;

测试加载核心配置类创建Spring容器

?

1

2

3

4

5

6

7

8

Test

public void testAnnoConfiguration ( ) throws Exception {

ApplicationContext applicationContext = new AnnotationConfigApplicationContext (SpringConfiguration. class ) ;

UserService userService = (UserService)applicationContext.getBean ( "userService" );

userService.save () ;

Datasource dataSource = (Datasource)applicationContext.getBean ( "dataSource" ) ;

Connection connection = dataSource.getConnection() ;

System.out.println (connection);

Spring整合Junit

原始Junit测试Spring的问题
在测试类中,每个测试方法都有以下两行代码:

?

1

2

ApplicationContext ac = new ClassPathxmlApplicationContext ( "bean.xml " );

IAccountService as = ac.getBean ( "accountservice" ,IAccountService. class )

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它

将需要进行测试Bean直接在测试类中进行注入

Spring集成Junit步骤

1、导入spring集成Junit的坐标
2、使用@Runwith注解替换原来的运行期
3、使用@contextConfiguration指定配置文件或配置类
4、使用@Autowired注入需要测试的对象
5、创建测试方法进行测试

1、导入spring集成Junit的坐标

?

1

2

3

4

5

6

7

8

9

10

11

< dependency >

   < groupId >org.springframework</ groupId >

   < artifactId >spring-test</ artifactId >

   < version >5.0.5.RELEASE</ version >

</ dependency >

     < dependency >

       < groupId >junit</ groupId >

       < artifactId >junit</ artifactId >

       < version >4.12</ version >

       < scope >test</ scope >

</ dependency >

2、使用@Runwith注解替换原来的运行期

?

1

2

3

@RunWith (SpringJUnit4ClassRunner. class )

public class SpringJunitTest {

}

3、使用@contextConfiguration指定配置文件或配置类

?

1

2

3

4

5

6

@RunWith (SpringJUnit4ClassRunner. class )

//加载Spring核心配置文件

//@ContextConfiguration("classpath:applicationContext.xml")

//加载Spring核心配置类

@ContextConfiguration (classes = {SpringCofiguration. class })

public class SpringJunitTest {

4、使用@Autowired注入需要测试的对象

?

1

2

3

4

5

6

7

@RunWith (SpringJUnit4ClassRunner. class )

@ContextConfiguration (classes = {SpringCofiguration. class })

public class SpringJunitTest {

 

     @Autowired

     private UserService userService;

}

5、创建测试方法进行测试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@RunWith (SpringJUnit4ClassRunner. class )

@ContextConfiguration (classes = {SpringCofiguration. class })

public class SpringJunitTest {

 

     @Autowired

     private UserService userService;

 

     @Test

     public void test1() throws SQLException {

         userService.save();

     }

 

}

到此这篇关于Java Spring详解如何配置数据源注解开发以及整合Junit的文章就介绍到这了,更多相关Java Spring内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/weixin_48838340/article/details/120769535

查看更多关于Java Spring详解如何配置数据源注解开发以及整合Junit的详细内容...

  阅读:25次