首页 > 其他分享 >Spring 02 Spring注解开发

Spring 02 Spring注解开发

时间:2023-09-22 11:55:24浏览次数:42  
标签:02 jdbc userDao Spring void class dataSource 注解 public

 dao层

public interface UserDao {
    void insertUser();
}

实现类
/*@Component(value = "userDao") 配置到实例里去 或者直接用下面的Repository*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public void insertUser() {
        System.out.println("持久层 添加用户");
    }
}

service层

public interface UserService {
    void insertUser();
}

实现类
@Component("userService") /*或 @Service("userService")*/
public class UserServiceImpl implements UserService {

    @Autowired /*按照类型自动注入*/
    @Qualifier("userDao")/*按照名称自动注入 不能单独使用,必须与@Autowired一起使用*/
  //  @Resource(name = "userDao")/*java的注解,用于代替@Autowired和 @Qualifier  相当于上面两个一起*/
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void insertUser() {
        System.out.println("业务层 添加用户");
        userDao.insertUser();
    }
}

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/myb?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123

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

    <!-- 有多个时 location="classpath:jdbc.properties,jdbc2.properties"-->
    <context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="userDao" class="com.dao.impl.UserDaoImpl"/>

    <!--注解扫描-->
    <context:component-scan base-package="com"/><!--扫描所有包,或者用逗号隔开com.dao.iml,com.service.iml-->

</beans>

test

    @Test
    public void testUserServiseAnno(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.insertUser();
    }

 

数据池加载的几种方法:

 导入第三方bean

方法一:

SpringConfih.java

@Configuration//表示该类是Spring配置类,用于代替ApplicationContext.xml
@ComponentScan(value = {"com.dao.impl","com.service.impl"})
@Import(value = {DataSourseConfig.class})/*导入第三方bean*/public class SpringConfig {
}
DataSourseConfig.java
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
 public class DataSourseConfig {
    @Bean
public DataSource dataSource(){
DruidDataSource dataSource= new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3307/myb?useSSL=false&useUnicode=true&characterEncoding=UTF-8");
dataSource.setUsername("root");
dataSource.setPassword("123");
return dataSource;
}
}

test

   @Test
    public void testConfiguration(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.insertUser();
    }

方法二:使用jdbc.properties

SpringConfih.java

@Configuration//表示该类是Spring配置类,用于代替ApplicationContext.xml
@ComponentScan(value = {"com.dao.impl","com.service.impl"})
@Import(value = {DataSourseConfig.class})/*导入第三方bean*/
@PropertySource(value = "classpath:jdbc.properties")
public class SpringConfig {
}

DataSourseConfig.java
 public class DataSourseConfig {
    @Value("${jdbc.driver}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource= new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

 

test

@Test
public void testDataSource() throws SQLException {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
DataSource dataSource = context.getBean("dataSource",DataSource.class);
System.out.println(dataSource.getConnection());
}

 

标签:02,jdbc,userDao,Spring,void,class,dataSource,注解,public
From: https://www.cnblogs.com/oyww-2027/p/17721993.html

相关文章

  • 2021-2022 ICPC Northwestern European Regional Programming Contest (NWERC 2021)
    A.AccessDenied先问若干次,问出长度,然后再一位一位的问即可。#include<bits/stdc++.h>usingnamespacestd;intinput(){strings;getline(cin,s);if(s=="ACCESSGRANTED")exit(0);intt=0;for(autoi:s){if(i&g......
  • 已解决 File “F:\File_Anaconda\2020CV\yolov5-master\20200701.py“, line 5 Sy
    已解决File“F:\File_Anaconda\2020CV\yolov5-master\20200701.py”,line5SyntaxError:Non-UTF-8codestartingwith‘\xc0’infileF:\File_Anaconda\2020CV\yolov5-master\20200701.pyonline5,butnoencodingdeclared;seehttp://python.org/dev/peps/pe......
  • 2023-09-21 裸k交易法 日内模型 低开
    低开高走  低开低走  ......
  • 041802114金晶的自我介绍~
    我的学号041802114;我是退役大学生士兵金晶,在部队是一名医疗救护员;我的爱好是运动还有看书;推荐紫荆园二楼的漳州鸭面;最近常听的歌我推荐一首lauv的《parisintherain》;想要说些什么呢,那就是“勇敢的人先享受世界”......
  • [CSP-J 2021] 插入排序
    题目描述插入排序是一种非常常见且简单的排序算法。小Z是一名大一的新生,今天H老师刚刚在上课的时候讲了插入排序算法。假设比较两个元素的时间为\(\mathcalO(1)\),则插入排序可以以\(\mathcalO(n^2)\)的时间复杂度完成长度为\(n\)的数组的排序。不妨假设这\(n\)个数......
  • Buuctf——[网鼎杯 2020 青龙组]AreUSerialz
    这是一道序列化的题目<?phpinclude("flag.php");highlight_file(__FILE__);classFileHandler{protected$op;protected$filename;protected$content;function__construct(){$op="1";$filename="/......
  • [代码随想录]Day51-单调栈part02
    题目:503.下一个更大元素II思路:总之就是走两次nums,可以拼接,也可以用下面的取余方式。代码:funcnextGreaterElements(nums[]int)[]int{lens:=len(nums)res:=make([]int,lens)fori:=0;i<lens;i++{res[i]=-1}stack:=make(......
  • 【2023-09-21】家庭真相
    20:00凡益之道,与时偕行。对历史能看得多深,对未来就能看得多远。                                                 ——XXX昨天下班,正常6点我就离开公司,直接回家。我晚......
  • 2023.09.21
      今天学习了数据结构栈和队列。采用顺序存储的栈称为顺序栈,它利用一组地址连续的存储单元存放自栈底到栈顶的数据元素,同时附设一个指针(top)指示当前栈顶元素的位置。若存储栈的长度为StackSize,则栈顶位置top必须小于StackSize。当栈存在一个元素时,top等于0,因此通常把空栈的判......
  • Couchdb-权限绕过--命令执行--(CVE-2017-12635)&&(CVE-2017-12636)--H2database命令执
    Couchdb-权限绕过--命令执行--(CVE-2017-12635)&&(CVE-2017-12636)--H2database命令执行--(CVE-2022-23221)环境概述采用Vulfocus靶场环境进行复现,搭建操作和文章参考具体搭建教程参考vulfocus不能同步的解决方法/vulfocus同步失败。CouchdbCVE-2017-12635权限绕过漏洞概述A......