注解配置和xml配置要實現的功能都是一樣的抖坪,都是要降低程序間的耦合壹蔓。只是配置的形式不一樣匠襟。
1.開發(fā)環(huán)境搭建
- 拷貝jar包到工程
- 在類的根路徑下創(chuàng)建一個任意名稱的xml文件(不能是中文)
給配置文件導入約束
約束在spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
目錄下的
bean.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">
</beans>
然后就可以開始使用注解了
2.常用注解
①用于創(chuàng)建bean對象
-
@Component
作用:相當于配置了一個bean標簽
出現的位置:類上面
屬性:value家夺。value的值是指定bean的id脱柱,當不寫,默認值是當前類的短名首字母改小寫
還是CustomerServiceImpl.java類
package com.edu.services.Impl;
import com.edu.services.ICustomerService;
import org.springframework.stereotype.Component;
@Component(value = "customerServiceImpl")
public class CustomerServiceImpl implements ICustomerService {
@Override
public void saveCustomer() {
System.out.println("執(zhí)行了保存用戶");
}
}
配置bean.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">
<!-- 告知spring框架在拉馋,讀取配置文件榨为,創(chuàng)建容器時,掃描注解煌茴,依據注解創(chuàng)建對象随闺,并存入容器中 -->
<context:component-scan base-package="com.edu"></context:component-scan>
</beans>
用client.java測試
package com.edu.ui;
import com.edu.services.ICustomerService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ICustomerService cs = (ICustomerService) ac.getBean("customerServiceImpl");
cs.saveCustomer();
}
}
- 由
@Component
注解衍生了一下三個注解,他們的作用及屬性都是一模一樣的蔓腐。-
@Controller
一般用于表現層的注解矩乐。 -
@Service
一般用于業(yè)務層的注解。 -
@Repository
一般用于持久層的注解合住。
-
②用于注入數據
-
@Autowired
作用:自動按照類型注入绰精。當使用注解注入屬性時,set方法可以省略透葛。它只能注入其他bean類型笨使。當有多個類型匹配時,使用要注入的對象變量名稱作為bean的id僚害,在spring容器查找硫椰,找到了也可以注入成功。找不到就報錯萨蚕。
CustomerServiceImpl.java
package com.edu.services.Impl;
import com.edu.dao.ICustomerDao;
import com.edu.services.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Service(value = "customerServiceImpl")
public class CustomerServiceImpl implements ICustomerService {
@Autowired
private ICustomerDao customerDao = null;
@Override
public void saveCustomer() {
System.out.println("業(yè)務層調用持久層");
customerDao.saveCustomer();
}
}
-
@Qualifier
作用:在自動按照類型注入的基礎之上靶草,再按照Bean的id注入。它在給類成員注入時不能獨立使用岳遥,必須和@Autowire一起使用奕翔;但是給方法參數注入時,可以獨立使用浩蓉。
屬性:value派继,用于指定bean的id
-
@Resource
作用:直接按照bean的id注入
屬性:name宾袜,用于指定的bean的id
以上三個注解都是用于注入其他的bean類型的。
-
@Value
作用:用于注入基本類型和String類型驾窟∏烀ǎ可以借助spring的el表達式讀取properties文件中的配置。
屬性:value绅络,用于指定要注入的數據月培。
CustomerServiceImpl.java
package com.edu.services.Impl;
import com.edu.dao.ICustomerDao;
import com.edu.services.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service(value = "customerServiceImpl")
public class CustomerServiceImpl implements ICustomerService {
@Value("你是豬")
private String name;
@Resource(name = "customerDaoImpl")
private ICustomerDao customerDao = null;
@Override
public void saveCustomer() {
System.out.println("業(yè)務層調用持久層..."+name);
customerDao.saveCustomer();
}
}
③用于改變作用范圍的
-
@Scope
作用:指定bean的作用范圍。
屬性:value恩急,指定范圍的值杉畜。
value的取值:singleton prototype request session globalsession
Client.java
package com.edu.ui;
import com.edu.services.ICustomerService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ICustomerService cs = (ICustomerService) ac.getBean("customerServiceImpl");
// cs.saveCustomer();
ICustomerService cs1 = (ICustomerService) ac.getBean("customerServiceImpl");
System.out.println(cs == cs1);
}
}
沒改scope之前
CustomerServiceImpl.java
package com.edu.services.Impl;
import com.edu.dao.ICustomerDao;
import com.edu.services.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service(value = "customerServiceImpl")
@Scope("prototype")
public class CustomerServiceImpl implements ICustomerService {
@Value("你是豬")
private String name;
@Resource(name = "customerDaoImpl")
private ICustomerDao customerDao = null;
@Override
public void saveCustomer() {
System.out.println("業(yè)務層調用持久層..."+name);
customerDao.saveCustomer();
}
}
IOC的注解已經完了,但是我們發(fā)現假栓,即使有spring的注解寻行,也依舊離不開xml配置文件,那么可不可以用注解代替xml配置文件呢匾荆,這就是spring的新注解拌蜘。
3.spring的純注解配置
- 項目工程目錄
- 用SpringConfiguration.java代替bean.xml
package com.edu.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration//表明當前類是一個配置類
@ComponentScan(basePackages = "com.edu")//配置要掃描的包
public class SpringConfiguration {
}
- 測試類的Client.java就不能用bean.xml了
package com.edu.ui;
import com.edu.config.SpringConfiguration;
import com.edu.services.ICustomerService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Client {
public static void main(String[] args) {
//1.獲取容器:由于我們已經沒有了xml文件,所以再用讀取xml方式就不能用了牙丽。
//這時需要指定加載哪個類上的注解
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.根據bean的id獲取對象
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
cs.saveCustomer();
}
}
新注解說明
@Configuration
作用:
用于指定當前類是一個spring配置類简卧,當創(chuàng)建容器時會從該類上加載注解。獲取容器時需要使用AnnotationApplicationContext
(有@Configuration
注解的類.class
)烤芦。
屬性:
value:用于指定配置類的字節(jié)碼@ComponentScan
作用:
用于指定spring在初始化容器時要掃描的包举娩。
和xml配置文件中的<context:component-scan base-package="com.itheima"/>
作用一樣
屬性:
basePackages:用于指定要掃描的包。和該注解中的value屬性作用一樣构罗。@PropertySource
作用:
用于加載.properties
文件中的配置铜涉。例如我們配置數據源時,可以把連接數據庫的信息寫到properties配置文件中遂唧,就可以使用此注解指定properties配置文件的位置芙代。
屬性:
value[]:用于指定properties文件位置。如果是在類路徑下盖彭,需要寫上classpath:@Import
作用:
用于導入其他配置類纹烹,在引入其他配置類時,可以不用再寫@Configuration
注解召边。當然铺呵,寫上也沒問題。
屬性:
value[]:用于指定其他配置類的字節(jié)碼隧熙。@Bean
作用:
該注解只能寫在方法上片挂,表明使用此方法創(chuàng)建一個對象,并且放入spring容器贞盯。它就相當于我們之前在xml配置中介紹的factory-bean
和factory-method
宴卖。
屬性:
name:給當前@Bean
注解方法創(chuàng)建的對象指定一個名稱(即bean的id)滋将。
運用新注解:
運用純注解對customer進行增刪改查
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
*/
@Configuration//它就是把當前類看成是spring的配置類
@ComponentScan({"com.itheima"})
@Import({JdbcConfig.class})//導入其他配置類
@PropertySource("classpath:config/jdbcConfig.properties")
public class SpringConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
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);
}
}
}
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/customer
jdbc.username=root
jdbc.password=root
Customer.java
package com.edu.domain;
import java.io.Serializable;
/**
* 客戶的實體類
* 我們使用DBUtils來操作。
* 它的使用要求蛾扇,實體類中的屬性和數據庫的字段必須一致
* @author zhy
*
*/
public class Customer implements Serializable {
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_address;
private String cust_phone;
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_address() {
return cust_address;
}
public void setCust_address(String cust_address) {
this.cust_address = cust_address;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
@Override
public String toString() {
return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_source=" + cust_source
+ ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_address=" + cust_address
+ ", cust_phone=" + cust_phone + "]";
}
}
ICustomerService.java
package com.edu.service;
import java.util.List;
import com.edu.domain.Customer;
/**
* 客戶的業(yè)務層接口
* @author zhy
*
*/
public interface ICustomerService {
/**
* 查詢所有客戶
* @return
*/
List<Customer> findAllCustomer();
/**
* 保存客戶
* @param customer
*/
void saveCustomer(Customer customer);
/**
* 更新客戶
* @param customer
*/
void updateCustomer(Customer customer);
/**
* 根據id刪除客戶
* @param custId
*/
void deleteCustomer(Long custId);
/**
* 根據id查詢客戶
* @param custId
* @return
*/
Customer findCustomerById(Long custId);
}
CustomerServiceImpl.java
package com.edu.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.edu.dao.ICustomerDao;
import com.edu.domain.Customer;
import com.edu.service.ICustomerService;
/**
* 客戶的業(yè)務層實現類
* @author zhy
*
*/
@Service(value = "customerService")
@Scope("prototype")
public class CustomerServiceImpl implements ICustomerService {
@Resource(name="customerDao")
private ICustomerDao customerDao ;
@Override
public List<Customer> 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);
}
}
ICustomerDao.java
package com.edu.dao;
import java.util.List;
import com.edu.domain.Customer;
/**
* 客戶的持久層接口
* @author zhy
*
*/
public interface ICustomerDao {
/**
* 查詢所有客戶
* @return
*/
List<Customer> findAllCustomer();
/**
* 保存客戶
* @param customer
*/
void saveCustomer(Customer customer);
/**
* 更新客戶
* @param customer
*/
void updateCustomer(Customer customer);
/**
* 刪除客戶
* @param custId
*/
void deleteCustomer(Long custId);
/**
* 根據id查詢客戶
* @param custId
* @return
*/
Customer findCustomerById(Long custId);
}
CustomerDaoImpl.java
package com.edu.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.edu.dao.ICustomerDao;
import com.edu.domain.Customer;
/**
* 客戶的持久層實現類
* @author zhy
*
*/
@Repository("customerDao")
public class CustomerDaoImpl implements ICustomerDao {
@Resource(name="runner")
private QueryRunner runner ;
@Override
public List<Customer> findAllCustomer() {
try {
return runner.query("select * from cst_customer",new BeanListHandler<Customer>(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>(Customer.class),custId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
CustomerServiceTest.java
package com.edu.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.edu.domain.Customer;
import com.edu.service.ICustomerService;
import config.SpringConfiguration;
/**
* 測試客戶的業(yè)務層
* @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<Customer> 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("北京市順義區(qū)");
cs.updateCustomer(c);
}
@Test
public void testDeleteCustomer() {
cs.deleteCustomer(95L);
}
@Test
public void testFindCustomerById() {
Customer c = cs.findCustomerById(94L);
System.out.println(c);
}
}