Spring_使用註解進行開發
阿新 • • 發佈:2020-07-31
使用註解開發
1、導包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
2、使用註解需要匯入 context 約束,增加對註解的支援
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 開啟註解支援 --> <context:annotation-config/> <!-- 指定指定的包,可以掃描包下的所有註解 --> <context:component-scan base-package="com.qilu.bean" /> </beans>
3、編寫bean類
@Component
public class User {
private String name;
}
@Component就相當於
預設的bean是類的小寫
@Component:元件,放在類上,說明這個類被Spring管理了,就是bean!
@Component public class User { @Value("張三") private String name; @Value("張三") public void setName(String name){ this.name = name; } }
@Value就相當於
放在屬性上和set方法上都行
4、衍生的註解:
@Component 有幾個衍生的註解,我們在web開發中,會按mvc三成架構分層!
- dao【@Repository】
- service【@Service】
- controller【@Controller】
此時,需要掃描全部的包:
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 開啟註解支援 -->
<context:annotation-config/>
<!-- 指定指定的包,可以掃描包下的所有註解 -->
<context:component-scan base-package="com.qilu" />
</beans>
5、自動裝配的註解
- @Autowired:自動裝配,通過型別,也可以用註解@Qualifier(value="xxx")配合來指定名字裝配
- @Nullable:欄位標記了這個註解,說明這個欄位可以為null
- @Resource:自動裝配,預設通過名字,如果找不到名字,則通過型別來實現!如果兩個都找不到,則報錯!
6、作用域
@Component
@Scope("singleton | prototype") //單例模式 | 原型模式
public class User {
private String name;
}
7、總結:
xml與註解:
- xml更加萬能,適用於任何場合!維護簡單方便
- 註解不是自己類使用不了,維護相對複雜!
- xml與註解最佳實踐:
- xml用來管理bean;
- 註解只負責屬性的注入;