热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Spring入门(一)

Sp

点击蓝字   关注我们


1.Spring配置数据源

1.1 数据源(连接池)的作用


数据源(连接池)的出现是为了提高程序性能的


事先实例化数据源,初始化部分连接资源


使用连接资源时从数据源中获取


使用完毕后将连接资源归还给数据源


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


1.2 数据源的手动创建

1.2.1原生写法


①导入数据源的坐标和数据库驱动坐标

<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>

<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>

<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.16version>
dependency>


②创建数据源对象


③设置数据源的基本连接数据

@Test
// c3p0
public void testsql() throws Exception {
//创建数据源
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 设置数据源参数
// version 5
// dataSource.setDriverClass("com.mysql.jdbc.Driver");
// dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springlearn");
// version 8
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springlearn?useSSL=false&serverTimezOne=UTC&characterEncoding=UTF-8");
dataSource.setUser("root");
dataSource.setPassword("root");
// 获取连接对象
Connection cOnnection= dataSource.getConnection();
System.out.println(connection);
// 关闭资源
connection.close();
}


@Test
// druid
public void testsql1() throws Exception {
//创建数据源
DruidDataSource dataSource = new DruidDataSource();
// 设置数据源参数
// version 5
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost:3306/test");
// version 8
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springlearn?useSSL=false&serverTimezOne=UTC&characterEncoding=UTF-8");
dataSource.setUsername("root");
dataSource.setPassword("root");
// 获取连接对象
Connection cOnnection= dataSource.getConnection();
System.out.println(connection);
// 关闭资源
connection.close();
}

    

④使用数据源获取连接资源和归还连接资源


1.2.2读取配置文件写法

@Test
public void testsqlproperties() throws Exception {
// 获取配置文件,直接在resources文件夹下以properties结尾的文件
ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
// 创建数据源
ComboPooledDataSource dataSource =new ComboPooledDataSource();
// 设置数据源参数
dataSource.setDriverClass(resourceBundle.getString("jdbc.driver"));
dataSource.setJdbcUrl(resourceBundle.getString("jdbc.url"));
dataSource.setUser(resourceBundle.getString("jdbc.username"));
dataSource.setPassword(resourceBundle.getString("jdbc.password"));
// 获取连接对象
Connection cOnnection= dataSource.getConnection();
System.out.println(connection);
// 关闭资源
connection.close();
}

    

1.3Spring创建数据源

1.3.1原生的写法

引入对应依赖

由于需要spring管控创建的类是引用的(已存在),直接配置文件配置即可

配置bean

"dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="com.mysql.cj.jdbc.Driver">property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn?useSSL=false&serverTimezOne=UTC&characterEncoding=UTF-8">property>
<property name="user" value="root">property>
<property name="password" value="root">property>
bean>

   从spring容器获取bean

@Test
public void testsqlspring() throws Exception {
// 读取配置文件
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取bean
ComboPooledDataSource dataSource = (ComboPooledDataSource) app.getBean("dataSource");
// 获取连接
Connection cOnnection= dataSource.getConnection();
System.out.println(connection);
connection.close();
}

   

1.3.2解耦配置内容写法

applicationContext.xml加载jdbc.properties配置文件

命名空间:xmlns:cOntext="http://www.springframework.org/schema/context"


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


然后在Spring容器加载properties文件


<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.xsd
">



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


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


<property name="driverClass" value="${jdbc.driver}">property>
<property name="jdbcUrl" value="${jdbc.url}">property>
<property name="user" value="${jdbc.username}">property>
<property name="password" value="${jdbc.password}">property>
bean>
beans>


2.Spring注解开发


2.1 Spring原始注解

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


注解

说明

@Component


使用在类上用于实例化Bean

@Controller


使用在web层类上用于实例化Bean

@Service


使用在service层类上用于实例化Bean

@Repository


使用在dao层类上用于实例化Bean

@Autowired


使用在字段上用于根据类型依赖注入

@Qualifier


搭配@Autowired一起使用,根据名称进行依赖注入

@Resource


相当于@Autowired+@Qualifier,按照名称进行注入

@Value


注入普通属性

@Scope


标注Bean的作用范围

@PostConstruct


使用在方法上标注该方法是Bean的初始化方法

@PreDestroy


使用在方法上标注该方法是Bean的销毁方法


先开启注解扫描


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

    

Dao层

//接口
public interface StudentDao {
public void study();
}


//实现类
//
//@Component("studentDao")
//区分dao层
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
public void study() {
System.out.println("studying******");
}
}


Service层

//接口
public interface StudentService {
public void study();
}


//实现类
//
//@Component("studentService")
//区分service层
@Service("studentService")
public class StudentServiceImpl implements StudentService {


//
//@Autowired
//@Qualifier("studentDao") //是根据id的内容 从spring容器中进行匹配的,与autowired使用
@Resource(name = "studentDao") //等同于 @Autowired + @Qualifier
private StudentDao studentDao;


public void study() {
studentDao.study();
}
}


测试类

@Test
public void testzhujie(){
ApplicationContext app =new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService = (StudentService) app.getBean("studentService");
studentService.study();
}

    




其他常用注解

@Value("普通数据")
private String str;
// 容器中的bean的数值
@Value("${jdbc.driver}")
private String sqldriver;
@PostConstruct
public void init(){
System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法.....");
}

    


2.2Spring引入文件和扫描类型注解

减少配置文件,使用注解简易开发

注解

说明

@Configuration


用于指定当前类是一个 Spring   配置类,当创建容器时会从该类上加载注解

@ComponentScan


用于指定 Spring   在初始化容器时要扫描的包。  作用和在 Spring   的 xml 配置文件中的   一样

@Bean


使用在方法上,标注将该方法的返回值存储到   Spring   容器中

@PropertySource


用于加载.properties   文件中的配置

@Import


用于导入其他配置类

创建Spring核心配置类

@Configuration //Spring的核心配置文件
//
@ComponentScan("com.joyfully")
//
@Import({SQLDataSource.class})
public class SpringConfiguration {
}


创建数据源配置文件类

//
@PropertySource("classpath:jdbc.properties")
public class SQLDataSource {
//注入内容
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;


//spring容器创建一个跟方法返回值类型相同的bean
@Bean("dataSource")
public DataSource getDataSource() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}


其他Service层和Dao层不变

测试

@Test
public void testzhujie1(){
ApplicationContext app =new AnnotationConfigApplicationContext(SpringConfiguration.class);
StudentService studentService = (StudentService) app.getBean("studentService");
studentService.study();
}

    


2.3Spring集成Junit测试

步骤:

①导入spring集成Junit的坐标


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


③使用@ContextConfiguration指定配置文件或配置类


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


⑤创建测试方法进行测试


引入坐标

<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>


具体实现:

//使用那个运行
@RunWith(SpringJUnit4ClassRunner.class)
//配置文件的方式
//@ContextConfiguration("classpath:applicationContext.xml")
//配置类的方式
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringTest {
//注入需要测试的对象
@Autowired
private StudentService studentService;


@Autowired
private DataSource dataSource;
@Test
public void test1(){
studentService.study();
System.out.println(dataSource);
}
}




END





推荐阅读
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 本文介绍了解决java开源项目apache commons email简单使用报错的方法,包括使用正确的JAR包和正确的代码配置,以及相关参数的设置。详细介绍了如何使用apache commons email发送邮件。 ... [详细]
  • 精讲代理设计模式
    代理设计模式为其他对象提供一种代理以控制对这个对象的访问。代理模式实现原理代理模式主要包含三个角色,即抽象主题角色(Subject)、委托类角色(被代理角色ÿ ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 电话号码的字母组合解题思路和代码示例
    本文介绍了力扣题目《电话号码的字母组合》的解题思路和代码示例。通过使用哈希表和递归求解的方法,可以将给定的电话号码转换为对应的字母组合。详细的解题思路和代码示例可以帮助读者更好地理解和实现该题目。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • C语言注释工具及快捷键,删除C语言注释工具的实现思路
    本文介绍了C语言中注释的两种方式以及注释的作用,提供了删除C语言注释的工具实现思路,并分享了C语言中注释的快捷键操作方法。 ... [详细]
  • 本文介绍了一种划分和计数油田地块的方法。根据给定的条件,通过遍历和DFS算法,将符合条件的地块标记为不符合条件的地块,并进行计数。同时,还介绍了如何判断点是否在给定范围内的方法。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
author-avatar
mobiledu2502869603
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有