天天看點

基于注解裝配Bean

  • 注解:就是一個類,@注解名
  • 開發中, 使用注解取代xml配置檔案
@Component("id")取代<bean id="" class="">
           
  1. 注解使用的前提,添加命名空間,讓spring掃描含有注解的類
<?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">

<!-- 元件掃描,掃描含有注解的類 -->
  <context:component-scan base-package="soundsystem" />

</beans>
           

2.web開發,提供3個@Component注解衍生注解(功能一樣)取代

@Repository :dao層

@Service:service層

@Controller:web層

3.依賴注入,給私有字段設定,也可以給setter方法設定

普通值:@Value("")

引用值:

方式1:按照【類型】注入

@Autowired

方式2:按照【名稱】注入1

@Autowired

@Qualifier(“名稱”)

方式3:按照【名稱】注入2

@Resource(“名稱”)

4.生命周期

初始化:@PostConstruct

銷毀:@PreDestroy

5.作用域

@Scope(“prototype”) 多例