> 文章列表 > Javaee spring jdbctemplate查询数据库,基于纯注解实现

Javaee spring jdbctemplate查询数据库,基于纯注解实现

Javaee spring jdbctemplate查询数据库,基于纯注解实现

为啥要用纯注解方式呢?因为xml中代码还是有点多,纯注解可以解决该问题

现在要做的很简单,就是用新建的SpringConfig这个类去替代xml

在测试类中加载核心配置类
SpringConfig类中
@Configuratio   Spring.xml配置类
@ComponentScan  <!--开启注解扫描-->
@PropertySource <!--加载属性配置文件-->
<!--数据源-->
<!--JdbcTempalte层-->

@Bean注解

//@Bean注解的作用,将@Bean放到一个有返回值为的方法上面,@Bean注解会将该方法的返回值放到ioc容器中,拿这个数据的时候要通过id找他。可自己指定id 格式:  @Bean("指定的id名字")

举个例子:创建一个返回值类型为DataSource的方法,此时@Bean注解会将该方法的返回值dataSource放到ioc容器中,当要使用dataSource,可通过指定的id

    @Bean("dataSource")public DataSource getDataSource() {ComboPooledDataSource dataSource=new ComboPooledDataSource();return dataSource;}

@Value注解:

Value注解的作用,是将资源文件中的数据,赋值给类中的成员属性

举个例子:此时,driver=com.mysql.cj.jdbc.Driver

    @Value("${jdbc.driver}")private  String  driver;

@Qualifier("id名")

@Qualifier("")的作用:多个数据源时,指定要用的数据源

jar包

项目结构:

源码:

SpringConfig
package wwx.config;import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;
import java.beans.PropertyVetoException;@Configuration             //加上@Configuration就相当于Spring.xml配置类
@ComponentScan("wwx")
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {@Value("${jdbc.driver}")private  String  driver;@Value("${jdbc.url}")private  String url;@Value("${jdbc.username}")private  String username;@Value("${jdbc.password}")private String password;//@Bean注解的作用,将@Bean放到一个返回值为DataSource的方法中,@Bean注解会将该方法的返回值放到ioc容器中,拿这个数据的时候//要通过id找他。可自己指定id 格式为@Bean("指定的id名字")// <!--数据源-->@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;}//容器中有一个数据源了,当用到以下模板时,容器会自动注入该数据源//若容器中有多个数据源,可以在方法中添加注解@Qualifier("id名")指定要用的数据源@Bean("jdbcTemplate")public JdbcTemplate getJDBCTemplate(@Qualifier("dataSource") DataSource dataSource){JdbcTemplate jdbcTemplate=new JdbcTemplate();jdbcTemplate.setDataSource(dataSource);return jdbcTemplate;}}

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/wwx?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

JDBCTest

package wwx.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import wwx.config.SpringConfig;
import wwx.dao.AccountDao;
import wwx.domain.Account;
import wwx.service.AccountService;
import wwx.service.AccountServiceImpl;import java.util.List;public class JDBCTest {@Testpublic void test01(){   //在test中创建了一个业务层对象,用业务层对象调用业务层中的调用方法,// 此时业务层方法中创建了Dao对象,调用了Dao方法//这样写的话,类与类直接耦合度太高了,// 举个例子,假设Dao包下的AccountDaoImpl突然没有了,AccountServiceImpl中代码就会报错//该如何解决呢,使用Spring:解耦,降低类内之间的联系,//也就是不用在AccountServiceImpl中去new Dao ,让Spring去new,如果要用到,通过注入方式注入进来
//        AccountService accountService=new AccountServiceImpl();
//        accountService.findAll();//加载配置文件// ApplicationContext app=new ClassPathXmlApplicationContext("Spring.xml");//获得bean//spring容器中id唯一//加载核心配置类ApplicationContext app=new AnnotationConfigApplicationContext(SpringConfig.class);//需要强转AccountService accountService = (AccountService) app.getBean("accountService");//调用方法List<Account> list = accountService.findAll();System.out.println(list+"在test里输出的哦");//此时删除AccountServiceImpl,编译不会报错,但是无法运行,耦合不能消除,但能降低}}
AccountDaoImpl
package wwx.dao;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import wwx.domain.Account;import java.util.List;@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {//创建jdbcTemplate成员变量,及set方法@Autowired@Qualifier("jdbcTemplate")private JdbcTemplate jdbcTemplate;//使用注解不需要使用set方法,可把set方法注释掉
//public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }//查询所有@Overridepublic List<Account> findAll() {System.out.println("我是Dao...");
//        JdbcTemplate jdbcTemplate=new JdbcTemplate();
//        jdbcTemplate.query();不用这种方式List<Account> list= jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));return list;}
}
AccountServiceImpl
package wwx.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import wwx.dao.AccountDao;
import wwx.dao.AccountDaoImpl;
import wwx.domain.Account;import java.util.List;
//在xml中<!--开启注解扫描-->
//    <context:component-scan base-package="wwx"></context:component-scan>
//在类名上面添加@Servie注解,相当于spring.xml中的<bean id="accountService" class="wwx.service.AccountServiceImpl">
//相当于在这个容器中创建有一个AccountServiceImpl这个类的对象,这个对象的id是类名首字母小写
//如果想指定类名,格式为@Service("指定名字"),在AccountDaoImpl中,执行与这里相同步骤,不过注解为@Repository,此时已经实现配置
//再接着进行注入,使用@Autowired注解,此注解是根据类型注入的,看容器中是否有这个接口类型配合使用@Qualifier
//使用注解不需要使用set方法,可把set方法注释掉
//此时实现我们自己写的类,用注解,jar包中的类用xml,将xml中的Service层,Dao层注释掉
@Service("accountService")
public class AccountServiceImpl implements AccountService {@Autowired              //<property name="accountDao" ref="accountDao"></property>@Qualifier("accountDao")private AccountDao accountDao;//创建accountDao//    public void setAccountDao(AccountDao accountDao) {
//        this.accountDao = accountDao;
//    }@Overridepublic List<Account> findAll() {System.out.println("我是service...");//  AccountDao accountDao=new AccountDaoImpl();List<Account> list = accountDao.findAll();return list;}
}

AccountDao

package wwx.dao;import wwx.domain.Account;import java.util.List;public interface AccountDao {//查询所有public List<Account> findAll();
}

AccountService

package wwx.service;import wwx.domain.Account;import java.util.List;public interface AccountService {//查询所有public List<Account> findAll();
}

运行效果图: