一,使用注解:
在spring的配置文件applicationContext.xml中,加入注解掃描。配置項就配置了對指定的包進行掃描,以實現依賴注入。
<?xml version="1.0" encoding="UTF-8"?> <span style="font-size:18px;"><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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <aop:aspectj-autoproxy/> <context:annotation-config/> <context:component-scan base-package="com.test" /> //去哪掃描 </beans>
二,常見注解:
@Controller @Service @Autowired @RequestMapping @RequestParam @ModelAttribute @Cacheable @CacheFlush @Resource @PostConstruct @PreDestroy @Repository @Component (不推薦使用) @Scope @SessionAttributes @InitBinder @Required @Qualifier
三,常用spring注解:
@Controller(運用於表現層)
使用@Controller注解標識UserAction之后,就表示要把UserAction交給Spring容器管理,在Spring容器中會存在一個名字為"userAction"的action,這個名字是根據UserAction類名來取的。注意:如果@Controller不指定其value【@Controller】,則默認的bean名字為這個類的類名首字母小寫,如果指定value【@Controller(value="UserAction")】或者【@Controller("UserAction")】,則使用value作為bean的名字。
這里的UserAction還使用了@Scope注解,@Scope("prototype")表示將Action的范圍聲明為原型,可以利用容器的scope="prototype"來保證每一個請求有一個單獨的Action來處理,避免struts中Action的線程安全問題。spring 默認scope是單例模式(scope="singleton"),這樣只會創建一個Action對象,每次訪問都是同一Action對象,數據不安全,struts2 是要求每次次訪問都對應不同的Action,scope="prototype" 可以保證當有請求的時候都創建一個Action對象
@Controller @Scope("prototype") public class UserAction extends BaseAction<User>{ }
@ Service(運用於業務邏輯層)
注意,@service注解是在服務接口的實現類下,而不是接口中使用。
這里很好的體現了spring中的控制反轉,我們不在讓對象自己去實例化對象,去主動依賴對象,而是 專門用一個容器來創建對象,由IOC進行管理。實例:
Action要使用UserServiceImpl時,就不用主動去創建UserServiceImpl的實例了,創建UserServiceImpl實例已經交給Spring來做了,Spring把創建好的UserServiceImpl實例給Action,Action拿到就可以直接用了。Action由原來的主動創建UserServiceImpl實例后就可以馬上使用,變成了被動等待由Spring創建好UserServiceImpl實例之后再注入給Action,Action才能夠使用。這說明Action對“UserServiceImpl”類的“控制權”已經被“反轉”了,原來主動權在自己手上,自己要使用“UserServiceImpl”類的實例,自己主動去new一個出來馬上就可以使用了,但現在自己不能主動去new“UserServiceImpl”類的實例,new“UserServiceImpl”類的實例的權力已經被Spring拿走了,只有Spring才能夠new“UserServiceImpl”類的實例,而Action只能等Spring創建好“UserServiceImpl”類的實例后,再“懇求”Spring把創建好的“UserServiceImpl”類的實例給他,這樣他才能夠使用“UserServiceImpl”,這就是Spring核心思想“控制反轉”,也叫“依賴注入”,“依賴注入”也很好理解,Action需要使用UserServiceImpl干活,那么就是對UserServiceImpl產生了依賴,Spring把Acion需要依賴的UserServiceImpl注入(也就是“給”)給Action,這就是所謂的“依賴注入”。對Action而言,Action依賴什么東西,就請求Spring注入給他,對Spring而言,Action需要什么,Spring就主動注入給他。
@Service("userService") public class UserServiceImpl implements UserService { }
@ Repository(運用於數據管理層)
筆者是使用工具反向生成的實體層數據Model跟mapper,所以也沒用到這個注解,不過這個就是簡單的向spring容器中注入一個Bean
@Repository(value="userDao") public class UserDaoImpl extends BaseDaoImpl<User> { }
四,常用springMVC注解:
@Autowired(按類型注入)
對類成員變量、方法及構造函數進行標注,完成自動裝配的工作。簡單來說就是調用Bean,告訴spring這個存在與被管理的容器中。
@Autowired 根據bean 類型從spring 上線文中進行查找,注冊類型必須唯一,否則報異常
@Autowired 標注作用於 Map 類型時,如果 Map 的 key 為 String 類型,則 Spring 會將容器中所有類型符合 Map 的 value 對應的類型的 Bean 增加進來,用 Bean 的 id 或 name 作為 Map 的 key。
@Autowired 還有一個作用就是,如果將其標注在 BeanFactory 類型、ApplicationContext 類型、ResourceLoader 類型、ApplicationEventPublisher 類型、MessageSource 類型上,那么 Spring 會自動注入這些實現類的實例,不需要額外的操作。
@Autowired private IReportService reportService ;
@Resource(按名稱注入)
跟@Autowired類似,@Resource 默認按bean的name進行查找,如果沒有找到會按type進行查找
@Resource private DataSource dataSource; // inject the bean named 'dataSource' @Resource(name="dataSource") @Resource(type=DataSource.class)
延伸問題:什么是按類型進行裝配,什么是按名稱進行裝配?
所謂按類型,就是當Spring容器中存在一個與指定屬性類型相同的bean,那么將該屬性進行自動裝配;如果存在多個該類型的bean,那么跑出異常,並指出不能使用按類型進行自動裝配;如果沒有找到匹配的bean,則什么事都不發生。
所謂按名稱,即根據屬性名進行自動裝配,此項會檢查Spring容器中與該屬性名完全一致的的bean,進行自動裝配。
@RequestMapping(映射請求地址)
用來處理請求地址映射的注解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。
其中有六個屬性,分別為:
1、 value, method;
value: 指定請求的實際地址,指定的地址可以是URI Template 模式(后面將會說明);
method: 指定請求的method類型, GET、POST、PUT、DELETE等;
2、consumes,produces
consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;
produces: 指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;
3、params,headers
params: 指定request中必須包含某些參數值是,才讓該方法處理。
headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。
@Controller @RequestMapping("/bbtForum.do") public class BbtForumController { @RequestMapping(params = "method=listBoardTopic") public String listBoardTopic(int topicId,User user) {} } @RequestMapping("/softpg/downSoftPg.do") @RequestMapping(value="/softpg/ajaxLoadSoftId.do", method=RequestMethod.POST) @RequestMapping(value="/osu/product/detail.do", params={"modify=false"}, method=RequestMethod.POST)
@RequestParam(獲取請求參數的值)
比如我們在瀏覽器的訪問地址是:localhost:8080/hello?id=1000,則拿到id的值,例如:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; } }
@PathVaribale (獲取url中的數據)
@RestController public class HelloController { @RequestMapping(value="/hello/{id}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id){ return "id:"+id; } }
@ResponseBody(返回類型為json)
作用: 該注解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。
使用時機:返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用;
五,常用springCloud注解
@SuppressWarnings(忽視某些警告)
用法:
public class Test { @SuppressWarnings({"deprecation"}) public static void main(String[] args) { Test.foo(); } }
作用:
關鍵詞 | 用途 |
deprecation | 使用了不贊成使用的類或方法時的警告 |
unchecked | 執行了未檢查的轉換時的警告,例如當使用集合時沒有用泛型 (Generics) 來指定集合保存的類型。 |
fallthrough | 當 Switch 程序塊直接通往下一種情況而沒有 Break 時的警告。 |
path | 在類路徑、源文件路徑等中有不存在的路徑時的警告。 |
serial | 當在可序列化的類上缺少 serialVersionUID 定義時的警告。 |
finally | 任何 finally 子句不能正常完成時的警告。 |
all | 關於以上所有情況的警告。 |
@Async && @EnableAsync
作用;
@EnableAsync注解的意思是可以異步執行,就是開啟多線程的意思。可以標注在方法、類上。
為了讓@Async注解能夠生效,需要在Spring Boot的主程序中配置@EnableAsync
@Async所修飾的函數不要定義為static類型,這樣異步調用不會生效
用法:
@Component public class AsyncDemo { private static final Logger log = LoggerFactory.getLogger(AsyncDemo.class); /** * 最簡單的異步調用,返回值為void */ @Async public void asyncInvokeSimplest() { log.info("asyncSimplest"); } /** * 帶參數的異步調用 異步方法可以傳入參數 * * @param s */ @Async public void asyncInvokeWithParameter(String s) { log.info("asyncInvokeWithParameter, parementer={}", s); } /** * 異常調用返回Future * * @param i * @return */ @Async public Future<String> asyncInvokeReturnFuture(int i) { log.info("asyncInvokeReturnFuture, parementer={}", i); Future<String> future; try { Thread.sleep(1000 * 1); future = new AsyncResult<String>("success:" + i); } catch (InterruptedException e) { future = new AsyncResult<String>("error"); } return future; } } //調用方式跟普通調用一樣 asyncDemo.asyncInvokeSimplest(); asyncDemo.asyncInvokeWithException("test"); Future<String> future = asyncDemo.asyncInvokeReturnFuture(100); System.out.println(future.get());
持續更行,若有不足之處,或是錯誤地方,麻煩大神指出,謝謝!