Spring中的註解:
註解含義:
用於創建對象的註解:
相當於:<bean id="" class="">
@Component註解:
作用:
把資源讓spring來管理。相當於在xml中配置一個bean,次註解使用在實體bean的頭部
@Component("accountService")
public class AccountServiceImpl implements AccountService {}
value = "accountService":相當於配置了bean標籤的id屬性,我們也可以不寫value的值默認bean的id是當前類的類名首字母小寫accountServiceImpl,單獨配置value時,可以省略value。
@Controller @Service @Repository:
三個註解都是針對@Component註解的衍生註解,他們的作用及屬性都是一模一樣的。
相當於: <property name="" ref=""> <property name="" value="">
他們只不過是提供了更加明確的語義化。
@Controller:一般用於表現層的註解。
@Service:一般用於業務層的註解。
@Repository:一般用於持久層的註解。
細節:如果註解中有且只有一個屬性要賦值時,且名稱是value,value在賦值時可以不寫。
用於注入數據的:
相當於: <property name="" ref=""> <property name="" value="">
@Autowired:
作用:
自動按照類型注入。當使用註解注入屬性時,set方法可以省略。它只能注入其他bean類型。當有多個類型匹配時,使用要注入的對象的變量名稱作爲bean的id,在spring容器查找,找到了也可以注入成功。找不到就報錯。
示例:
@Autowired
private AccountDao accountDao;
@Qualifier:
作用:
在自動按照類型注入的基礎之上,再按照Bean的id注入。它在給字段注入時不能獨立使用,必須和@Autowire一起使用,
但是給方法參數注入時,可以獨立使用。
屬性:
value:指定bean的id。
示例:
@Autowired
@Qualifier("accountDao2")指定將accountDao注入實體的變量名
private AccountDao accountDao;
給方法注入實參:
public JdbcTemplate craJdbcTemplate(@Qualifier("dataSource") DataSource dataSource){ }
@Resource:
作用:
直接按照Bean的id注入。它也只能注入bean類型。
屬性:
name:指定bean的id。
示例:
@Resource(name="accountDao")
private AccountDao accountDao;
@Value:
作用:
注入基本數據類型和String類型數據的
屬性:
value:用於指定值
示例1:
@Value("zahngsan")
private String name; name="zahngsan"
示例2:
//將配置文件jdbc.properties中的數據註解到
@Value("${jdbc.driverClass}")
private String driverClass;driverClass="com.mysql.jdbc.Driver"
用於改變作用範圍的:
相當於:<bean id="" class="" scope="">
@Scope:
作用:
指定bean的作用範圍。
屬性:
value:指定範圍的值。
取值:
singleton:默認的單例
prototype:多例
新註解說明:
@Configuration:
作用:
用於指定當前類是一個spring配置類,當創建容器時會從該類上加載註解。
獲取容器時需要使用AnnotationApplicationContext(有@Configuration註解的類.class)。
示例代碼:
/**
* spring的配置類,相當於applicationContext.xml文件
*/
@Configuration
public class SpringConfiguration {
}
@ComponentScan:
作用:
用於指定spring在初始化容器時要掃描的包。作用和在spring的xml配置文件中的:
<context:component-scan base-package="cn.itcast"></context:component-scan>
屬性:
Value(單獨使用可省略):用於指定要掃描的包。和標籤中的basePackages屬性作用一樣。
示例代碼:
/**
* spring的配置類,相當於bean.xml文件
*/
@Configuration
@ComponentScan("cn.itcast")
public class SpringConfiguration {
}
@Bean:
作用:
該註解只能寫在方法上,將方法的返回值作爲一個bean,並且放入spring容器。id就是name的屬性的值
屬性:
name:給當前@Bean註解方法創建的對象指定一個名稱(即bean的id)。
示例代碼:
@Bean(name="dataSource")
public DataSource createDataSource() throws Exception
{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/heima-26");
ds.setUser("root");
ds.setPassword("root");
return ds;
}
@PropertySource:
作用:
用於加載.properties文件中的配置。例如我們配置數據源時,可以把連接數據庫的信息寫到properties配置文件中,就可以使用此註解指定properties配置文件的位置。
屬性:
value[]:用於指定properties文件位置。如果是在類路徑下,需要寫上classpath:
示例代碼:
@PropertySource(value = { "classpath:jdbc.properties" })
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "dataSource")
public DataSource createDataSource() throws Exception {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driverClass);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}
}
@Import:
作用:
用於導入其他配置類,在引入其他配置類時,其他類上可以不用再寫@Configuration註解。當然,寫上也沒問題。
屬性:
value[]:用於指定其他配置類的字節碼。
示例代碼:
@Configuration
@ComponentScan("cn.itcast")
@Import(value = { JdbcConfig.class })
public class SpringConfiguration {
}
@Configuration//寫不寫都行
@PropertySource(value = { "classpath:jdbc.properties" })
public class JdbcConfig { }
Spring整合junit:
@RunWith:
作用:
替換掉junit的運行器,換成一個可以初始化spring容器的運行器。
屬性:
value:單獨配置時,value屬性名稱可以省略,配置SpringJUnit4ClassRunner.class來代替原來junit的運行器
@ContextConfiguration:
作用:
加載配置類或者xml配置文件
屬性:
value[]:用來指定xml配置文件的路徑
class[]: 用來指定配置類
示例:自動的加載配置文件的信息
//表示spring整合junit使用spring容器的運行器
@RunWith(SpringJUnit4ClassRunner.class)
//表示加載xml的配置的文件即可完成配置文件的加載
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
配置Aop註解:
@EnableAspectJAutoProxy:
聲明使用註解方式的AOP配置了:
@Configuration:
標註此類是一個配置的類相當於applicationContext.xml的加載配置的類:
@ComponentScan("com.itheima"):
標註此類相當於applicationContext.xml的加載配置的類,開啓包的全局的掃描的方式:
@Configuration//標註此類是一個配置的類
@ComponentScan("com.itheima")//掃描的類
@EnableAspectJAutoProxy//聲明使用註解方式的AOP配置了
public class SpringConfiguration {
}
@Aspect:
指定當前類是通知類寫在類上:
@Aspect//聲明這是一個切面類(通知類)裏面配置的有具體的通知的方法
@Service//將此類放到容器中
public class Logger {
}
@Before:
前置通知方法:
@Before("execution(* com.itheima.serviceImpl.*.*(..))")
public void beforePrintLog() {
System.out.println("前置通知執行了");
}
@after-returning:
後置通知方法:
@AfterReturning("execution(* com.itheima.serviceImpl.*.*(..))")
public void afterReturningPrintLog() {
System.out.println("後置通知執行了");
}
@after-throwing:
異常攔截通知方法:
@AfterThrowing("execution(* com.itheima.serviceImpl.*.*(..))")
public void afterThrowingPrintLog() {
System.out.println("異常通知執行了");
}
@after:
後通知方法:
@AfterReturning("execution(* com.itheima.serviceImpl.*.*(..))")
public void afterReturningPrintLog() {
System.out.println("後置通知執行了");
}
@PointCut:
抽取切點表達式:
@Pointcut("execution(* com.itheima.serviceImpl.*.*(..))")
public void pt1(){
}
@around:
環繞通知方法:
/**
* 環繞通知
* 問題:
* 當配置完環繞通知之後,沒有業務層方法執行(切入點方法執行)
* 分析:
* 通過動態代理的代碼分析,我們現在的環繞通知沒有明確的切入點方法調用
* 解決:
* spring框架爲我們提供了一個接口,該接口可以作爲環繞通知的方法參數來使用
* ProceedingJoinPoint。當環繞通知執行時,spring框架會爲我們注入該接口的實現類。
* 它有一個方法proceed(),就相當於invoke,執行目標方法
* <p>
* spring的環繞通知:
* 它是spring爲我們提供的一種可以在代碼中手動控制增強方法何時執行的方式。
*/
@Around("pt1()")
public Object around(ProceedingJoinPoint pjp) {
try {
System.out.println("增強了前置通知!");
Object obj = pjp.proceed();
System.out.println("增強了後置通知!");
return obj;
} catch (Throwable e) {
System.out.println("增強了異常通知!");
throw new RuntimeException(e);
} finally {
System.out.println("增強了最終通知!");
}
}
基於註解的事務管理:
@Transactional:
@Transactional 註解可以被應用於接口定義和接口方法、類定義和類的 public 方法上。
註解使用在類上表明此類下的所有的方法是一個基於註解的事務
定義在接口上,只有接口的代理的實現的類可認爲是基於註解的方法。因爲註解不能被繼承。
然而,請注意僅僅 @Transactional 註解的出現不足於開啓事務行爲,它僅僅是一種元數據,能夠被可以識別。要開啓註解的植物管理 <tx:annotation-driven/>:
SpringMvc中的註解:
@Controller:
Spring的Controller是Singleton的。這就意味着會被多個請求線程共享。因此,我們將控制器設計成無狀態類:
@RequestMapping:
在類前面定義,則將url和類綁定;(如果該類裏只有單個方法的話可以這樣寫,訪問該地址直接調用該方法):
示例代碼如下:
@Controller
@RequestMapping("/getUser")
public class UserController {
......
......
}
定義在方法上則會爲方法生成一個請求的路徑:
@RequestMapping("/hello")
public String getHello() {
return "index";
}
可以攜帶請求的參數 Rest風格(佔位符)的映射:
@RequestMapping(value=“/user/{name}/{id} ")
請求URL:http://localhost:8080/user/zhangsan/1001.do
這種方式雖然和通配符“*”類似,卻比通配符更加強大,佔位符除了可以起到通配的作用,最精要的地方是在於它還可以傳遞參數。
測試一:
@RequestMapping(value="show4/{name}/{id}")
public ModelAndView test4(){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg", "佔位符的映射:");
return mv;
}
與其相關:
@GetMapping:相當於@RequestMapping(method = RequestMethod.GET)
@PostMapping:相當於@RequestMapping(method = RequestMethod.POST)
@PutMapping:相當於@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping:相當於@RequestMapping(method = RequestMethod.DELETE)
@PathVariable:
與 Rest風格(佔位符)的映射一起使用獲取參數數據:
@RequestMapping(value="/show4/{name}/{id}")
public ModelAndView test4(@PathVariable("name")String name,@PathVariable("id")Long id){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg", "佔位符的映射:"+name+"..."+id);
return mv;
}
@PathVariable(“userId”) Long id, @PathVariable(“name”)String name獲取對應的參數:
@PathVariable(“key”)中的key必須和對應的佔位符中的參數名一致,而方法形參的參數名可任意取:
@RequestParam:
A) 常用來處理簡單類型的綁定,通過Request.getParameter() 獲取的String可直接轉換爲簡單類型的情況( String--> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因爲使用request.getParameter()方式獲取參數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值:
B)用來處理Content-Type: 爲 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST:
GET模式下,這裏使用了@PathVariable綁定輸入參數,非常適合Restful風格。因爲隱藏了參數與路徑的關係,可以提升網站的安全性,靜態化頁面,降低惡意攻擊風險。
POST模式下,使用@RequestBody綁定請求對象,Spring會幫你進行協議轉換,將Json、Xml協議轉換成你需要的對象。
C) 該註解有三個屬性: value、required、defaultValue:
value用來指定要傳入值的id名稱:
required用來指示參數是否必須綁定:
defaultValue用來指定在前端沒有傳值的情況下限定默認的值:
@RequestMapping(value="show19")
public String test19(Model model,@RequestParam(value="name")String name){
model.addAttribute("msg", "使用@RequestParam接收到的參數爲:"+name);
return "hello";
}
@ResponseStatus(value=HttpStatus.OK):如果不響應頁面,就需要響應狀態:
@RequestMapping(value = "show23")
@ResponseStatus(value=HttpStatus.OK)//不響應頁面,就需要響應個狀態碼
public void test23(@RequestParam("name")String name,
@RequestParam("age")Integer age,
@RequestParam("isMarry")Boolean isMarry, //可以將on或者1轉換爲true,0轉換爲false.
@RequestParam("income")Float income,
@RequestParam("interests")String[] interests) {
StringBuffer sb = new StringBuffer();
sb.append("name:"+name+"\n");
sb.append("age:"+age+"\n");
sb.append("isMarry:"+isMarry+"\n");
sb.append("income:"+income+"\n");
sb.append("interests:[");
for (String inter : interests) {
sb.append(inter+" ");
}
sb.append("]");
System.out.println(sb.toString());
}
@CookieValue使用方法同@RequestParam:獲取cookie的值:
@RequestMapping(value = "show22")
public String test22(Model model, @CookieValue("JSESSIONID")String jsessionid) {
model.addAttribute("msg", "jsessionid:" + jsessionid);
return "hello";
}
@ResponseBody:
當一個處理請求的方法標記爲@ResponseBody時,表示該方法需要輸出其他視圖(json、xml),springmvc會通過默認的json轉化器轉化輸出,但是需要引入相關的jar包:
<!--jackson支持json解析-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
/**
* 將list集合響應成json數據
* @return
*/
@RequestMapping(value="show28")
@ResponseBody//將數據響應成json格式的數據
public List<User> test28() {
List<User> list = new ArrayList<User>();
for(int i = 0;i< 20;i++) {
User user = new User();
user.setId(i+1L);
user.setUsername("zhangsan"+i);
user.setName("張三"+i);
user.setAge(18);
list.add(user);
}
return list;
}
@RequestBody:接收一個json並且轉換成一個對象
/**
* 將提交的json格式的數據封裝到user對象中
*
* @RequestBody():自動將json數據序列化成一個user對象
* @param model
* @param user
* @return
*/
@RequestMapping(value="show29")
public String test29(Model model,@RequestBody()User user) {
model.addAttribute("msg", user);
return "hello";
}
@RestController:
有時如果在一個Contoller中所有的方法都是用來響應json格式數據的,那麼如果有多個方法,就需要在多個方法上使用@ResponseBody,這樣太麻煩,springmvc提供了一個@RestController,將該註解使用在Controller類上,那麼該controller中的所有方法都默認是響應json格式的數據了。
Mybatis框架常用註解總結:
@Param:
使用@Param註解爲相應的查詢接口傳遞值,但是具體SQL語句中的參數要與@Param中定義的參數保持一致。
//mapper接口定義
List<Student> selectBetweenCreatedTimeAnno(@Param("begin")Date beginMonth, @Param("end")String endMonth);
//SQL語句
<select id="getAssessRecord" resultMap="SmuAssess">
select * from smu_assess_table3 where occurMonth between #{begin} and #{end}
</select>
@MapKey:
MyBatis使用@MapKey註解接收多個查詢記錄到Map中.
@MapKey("id")
public Map<Integer,Map<String,Object>>getUsers(Map<String,Object>param);
<select id="getUsers" resultType="java.util.Map" parameterType="java.util.Map">
select id,name,sex from t_user
</select>
返回的結果是
{1={name:jasion,sex:1},2={name:jack,sex=1}}
謝謝大家閱讀學習,如有錯誤歡迎留言指正ha。