导入jar包
bean.xml
Client.java
package com.itheima.ui;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.service.ICustomerService;
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ICustomerService cs1 =(ICustomerService) ac.getBean("customerService");
// System.out.println(cs);
// cs.saveCustomer();
ICustomerService cs2 =(ICustomerService) ac.getBean("customerService");
System.out.println(cs1 == cs2);
}
}
CustomerServiceImpl.java
package com.itheima.service.impl;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.itheima.dao.ICustomerDao;
import com.itheima.service.ICustomerService;
/**
* 客户的业务层实现类
* @author zhy
*
* 1、用于创建bean对象
* @Component
* 作用:就相当于配置了一个bean标签。
* 它能出现的位置:类上面
* 属性:value。含义是指定bean的id。当不写时,它有默认值,默认值是:当前类的短名首字母改小写。
* 由此注解衍生的三个注解:
* @Controller 一般用于表现的注解
* @Service 一般用于业务层
* @Repository 一般用于持久层
* 他们和@Component的作用及属性都是一模一样
* 2、用于注入数据的
* @Autowired
* 作用:自动按照类型注入。只要有唯一的类型匹配就能注入成功。
* 如果注入的bean在容器中类型不唯一时,它会把变量名称作为bean的id,在容器中查找,找到后也能注入成功。
* 如果没有找到一致的bean的id,则报错。
* 当我们使用注解注入时,set方法就不是必须的了。
* @Qualifier
* 作用:在自动按照类型注入的基础之上,再按照bean的id注入。它在给类成员注入数据时,不能独立使用。但是再给方法的形参注入数据时,可以独立使用。
* 属性:
* value:用于指定bean的id。
* @Resource
* 作用:直接按照bean的id注入。
* 属性:
* name:用于指定bean的id。
* 以上三个注解都是用于注入其他bean类型的。用于注入基本类型和String类型需要使用Value
* @Value:
* 作用:用于注入基本类型和String类型数据。它可以借助spring的el表达式读取properties文件中的配置。
* 属性:
* value:用于指定要注入的数据
* 3、用于改变作用范围的
* @Scope
* 作用:用于改变bean的作用范围
* 属性:
* value:用于指定范围的取值。
* 取值和xml中scope属性的取值是一样的。singleton prototype request session globalsession
* 4、和生命周期相关的
* 5、spring的新注解
*
*/
@Service("customerService")
@Scope("prototype")
public class CustomerServiceImpl implements ICustomerService {
@Value("泰斯特")
private String name;
// @Autowired
// @Qualifier("customerDao1")
@Resource(name="customerDao2")
private ICustomerDao customerDao = null;
@Override
public void saveCustomer() {
System.out.println("业务层调用持久层......"+name);
customerDao.saveCustomer();
}
}
xml方式可以避免修改源码,重启服务器,但是繁琐,文件过多,不好维护。
需要经常修改就选xml
修改项目
JdbcConfig.java
package config;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* Jdbc的配置类
* @author zhy
*
*/
public class JdbcConfig {
@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(name="runner")//它是把方法的返回值存入spring容器中。该注解有一个属性,name:用于指定bean的id。当不指定时它有默认值,默认值是方法的名称。
public QueryRunner createQueryRunner(@Qualifier("ds1")DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean(name="ds")
public DataSource createDataSource(){
try {
System.out.println(driver);//com.mysql.jdbc.Driver
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean(name="ds1")
public DataSource createDataSource1(){
try {
System.out.println(url);
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
SpringConfiguration.java
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* 一个spring的配置类
* 它的作用就相当于bean.xml
* @author zhy
*/
//commonent如果需要用类的对象,让spring管理,就配置,不然import就可以,避免占用容器内存
@Configuration//它就是把当前类看成是spring的配置类,用处不大,注解后不必写路径就可以找到
@ComponentScan({"com.itheima"})//配置要扫描的包
@Import({JdbcConfig.class})//导入其他配置类
@PropertySource("classpath:config/jdbcConfig.properties")
public class SpringConfiguration {
@Bean//把方法的返回值存入spring容器中该注解有一个属性,name:用于指定bean的id,默认值是方法的名称
public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day64_spring01
jdbc.username=root
jdbc.password=suntong
CustomerServiceImpl.java
package com.itheima.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import com.itheima.dao.ICustomerDao;
import com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;
/**
* 客户的业务层实现类
* @author zhy
*
*/
@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {
@Resource(name="customerDao")
private ICustomerDao customerDao ;
@Override
public List findAllCustomer() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
@Override
public void updateCustomer(Customer customer) {
customerDao.updateCustomer(customer);
}
@Override
public void deleteCustomer(Long custId) {
customerDao.deleteCustomer(custId);
}
@Override
public Customer findCustomerById(Long custId) {
return customerDao.findCustomerById(custId);
}
}
CustomerDaoImpl.java
package com.itheima.dao.impl;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;
import com.itheima.dao.ICustomerDao;
import com.itheima.domain.Customer;
/**
* 客户的持久层实现类
* @author zhy
*
*/
@Repository("customerDao")
public class CustomerDaoImpl implements ICustomerDao {
@Resource(name="runner")
private QueryRunner runner ;
@Override
public List findAllCustomer() {
try {
return runner.query("select * from cst_customer",new BeanListHandler(Customer.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveCustomer(Customer customer) {
try {
runner.update("insert into cst_customer(cust_name,cust_source,cust_industry,cust_level,cust_address,cust_phone)values(?,?,?,?,?,?)",
customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
customer.getCust_level(),customer.getCust_address(),customer.getCust_phone());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void updateCustomer(Customer customer) {
try {
runner.update("update cst_customer set cust_name=?,cust_source=?,cust_industry=?,cust_level=?,cust_address=?,cust_phone=? where cust_id=?",
customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
customer.getCust_level(),customer.getCust_address(),customer.getCust_phone(),customer.getCust_id());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteCustomer(Long custId) {
try {
runner.update("delete from cst_customer where cust_id = ? ",custId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public Customer findCustomerById(Long custId) {
try {
return runner.query("select * from cst_customer where cust_id = ? ",new BeanHandler(Customer.class),custId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
CustomerServiceTest.java
package com.itheima.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;
import config.SpringConfiguration;
/**
* 测试客户的业务层
* @author zhy
*
*/
public class CustomerServiceTest {
@Test
public void testFindAllCustomer() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
List list = cs.findAllCustomer();
for(Customer c : list){
System.out.println(c);
}
}
@Test
public void testSaveCustomer() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
Customer c = new Customer();
c.setCust_name("dbutils customer annotation");
cs.saveCustomer(c);
}
@Test
public void testUpdateCustomer() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
Customer c = cs.findCustomerById(94L);
c.setCust_address("北京市顺义区");
cs.updateCustomer(c);
}
@Test
public void testDeleteCustomer() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
}
@Test
public void testFindCustomerById() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
}
}
五个新注解都在项目中包含了
全是注解并不爽,如果用xml,新注解都不用,主要resource和component。
Spring整合junit
- 拷贝spring提供的整合jar包
spring-test-4.2.4.RELEASE.jar - 使用junit提供的一个注解,把原有的main函数替换掉,换成Spring提供的
@RunWith
更换的类:SpringJunit4ClassRunner - 使用Spring提供的注解告知Spring,配置文件或者注解类所在的位置
@ContextConfiguration
package com.itheima.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;
import config.SpringConfiguration;
/**
* 测试客户的业务层
* @author zhy
* spring整合junit
* 第一步:拷贝spring提供的整合jar包
* spring-test-4.2.4.RELEASE.jar
* 第二步:使用junit提供的一个注解,把原有的main函数替换掉,换成spring提供的
* @RunWith
* 要换的类:SpringJunit4ClassRunner
* 第三步:使用spring提供的的注解告知spring,配置文件或者注解类所在的位置
* @ContextConfiguration
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringConfiguration.class})
public class CustomerServiceTest {
@Autowired
private ICustomerService cs = null;
@Test
public void testFindAllCustomer() {
List list = cs.findAllCustomer();
for(Customer c : list){
System.out.println(c);
}
}
@Test
public void testSaveCustomer() {
Customer c = new Customer();
c.setCust_name("dbutils customer annotation");
cs.saveCustomer(c);
}
@Test
public void testUpdateCustomer() {
Customer c = cs.findCustomerById(94L);
c.setCust_address("北京市顺义区");
cs.updateCustomer(c);
}
@Test
public void testDeleteCustomer() {
cs.deleteCustomer(95L);
}
@Test
public void testFindCustomerById() {
Customer c = cs.findCustomerById(94L);
System.out.println(c);
}
}