狂神說Java:https://space.bilibili.com/95256449
@Component 放在類上,說明這個類被Spring管理了,就是bean
@Value 可以放在屬性上,也可以放在set方法上
@Repository dao層
@Service service層
@Controller controller層
@Scope 作用域
在Spring4之後,要使用註解開發,必須要保證aop的包導入了!
使用註解需要導入contex約束,增加註解的支持!
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
1、bean
@Component放在類上,說明這個類被Spring管理了,就是bean!
/**
* @author Administrator
* Component(組件) 等價於<bean id="user" class="com.kuang.pojo.User"/>
*/
@Component
public class User {
public String name = "張三";
}
2、屬性如何注入
@Value可以放在屬性上,也可以放在set方法上
@Value("張三")
public void setName(String name) {
this.name = name;
}
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author Administrator
* Component(組件)等價於<bean id="user" class="com.kuang.pojo.User"/>
*/
@Component
public class User {
/**
* Value 相當於 <property name="name" value="張三"/>
*/
@Value("張三")
public String name;
public void setName(String name) {
this.name = name;
}
}
3、衍生的註解
@Component有幾個衍生註解。我們在web開發中,會按照mvc三層架構分層!
dao【@Repository】
package com.kuang.dao;
import org.springframework.stereotype.Repository;
/**
* @author Administrator
*/
@Repository
public class UserDao {
}
service【@Service】
package com.kuang.service;
import org.springframework.stereotype.Service;
/**
* @author Administrator
*/
@Service
public class UserService {
}
controller【@Controller】
package com.kuang.controller;
import org.springframework.stereotype.Controller;
/**
* @author Administrator
*/
@Controller
public class UserController {
}
這4個註解功能都是一樣的,都是代表將某個類註冊到Spring容器中,裝配Bean
4、自動裝配註解
使用@AutoWired我們可以不編寫set方法,前提是你這個自動裝配的屬性在IOC(Spring)容器中存在且符合名字ByName!
如果@Autowired自動裝配的環境比較複雜,自動裝配無法通過一個註解完成的時候【@Autowired】。我們可以使用@Qualifier(value = "xxx")去配合@Autowired的使用,指定一個唯一的bean對象注入!
@Nullable 說明這個字段可以爲null
5、作用域
@Scope
原型模式
@Component
@Scope("prototype")
public class User {
/**
* Value 相當於 <property name="name" value="張三"/>
*/
@Value("張三")
public String name;
public void setName(String name) {
this.name = name;
}
}
單例模式
@Component
@Scope("singleton")
public class User {
/**
* Value 相當於 <property name="name" value="張三"/>
*/
@Value("張三")
public String name;
public void setName(String name) {
this.name = name;
}
}
6、小結
xml和註解
1、xml更加萬能,適用於任何場景!維護簡單方便
2、註解 不是自己類用不了,維護相對複雜
xml與註解最佳實踐
xml用來管理bean
註解只負責完成屬性的注入
我們在使用的過程中,只需要注意一個問題:必須讓註解生效,就需要開啓註解支持
<context:annotation-config/> <!--指定要掃描的包,這個包下的註解就會生效--> <context:component-scan base-package="com.kuang"/>