@(Spring)[Spring, ioc, 注解]
Spring IOC注解開發Spring的IOC的注解使用步驟創建項目引入jar包引入配置文件創建相關包和類將類的控制權交給Spring容器編寫測試依賴注入Spring的IOC注解的詳解Bean定義注解Bean依賴注入注解Bean的作用范圍的注解Bean的生命周期注解Spring的IOC的xml方式和注解方式比較XML和注解的比較contextcomponet-scan和contextannotation-config的區別
如果屬性有set方法,注解需要加到set方法上,如果沒有set方法直接在屬性上添加注解。
PS:如果不知道怎么配置Spring和junit單元測試集成,可以參考之前寫的博客《Spring集成單元測試》
原來需要使用XML配置的方式將id和類綁定,現在不需要這樣做了只需要在類上添加注解即可。
@Component
:組件 @Controller
:修飾web層類@Service
:修飾業務層類@Repository
:修飾持久層類@Component
是Spring提供的通用的組件注解,可以通過在類上使用該注解,將對應的類標記為Spring Bean,使用此功能需要在Spring配置文件中,開啟組件掃描,<context:component-scan base-package="包名"/>
。
@Component
和@Component("name")
的區別在于,前者只能通過Spring的按類型注入依賴,后者還能使用按名注入依賴。
@Controller
、@Service
和@Repository
這三個注解和@Component
的功能在目前的4.x.x版本都是一樣的,只是表明它是一個組件。不過通過在不同層使用相對應的注解,可以使注解更具有意義。在以后的版本中,Spring可能提供對這三個注解不同的增強。
如果屬性有set方法,注解需要加到set方法上,如果沒有set方法直接在屬性上添加注解。
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SpringIOCAnnotationTest { // @Value("Switch") private String name; @Value("Switch") public void setName(String name) { this.name = name; } @Test public void test2() { System.out.println(name); }}PS:如果同時在屬性和set方法上添加了注解,那么set方法上的注解將會覆蓋屬性上的。
普通類型的屬性@Value
:注入普通類型屬性@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SpringIOCAnnotationTest { @Value("Switch") private String name; @Test public void test2() { System.out.println(name); }}對象類型的屬性 @Resource
:注入對象類型@Autowired
:注入對象類型,默認按照類型注入。結合@Qualifier
注解完成按名稱的注入。 @Qualifier
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SpringIOCAnnotationTest { // 按bean類型注入 // @Resource // 按名注入,需要組件設置名稱 // @Resource(name = "userService") // 和上面功能一樣,按名注入 @Qualifier("userService") @Autowired private UserService userService; @Test public void test1() { userService.save(); }}@Scope
:在類上添加的,控制類生成的時候采用單例還是多例。 取值: singleton
:單例prototype
:多例request
:request域,需要在web環境session
:session域,需要在web環境application
: context域,需要在web環境globalsession
集群環境的session域,需要在web環境PS:可以到WebApplicationContext
接口和ConfigurableBeanFactory
類中找到@Scope
的取值。
@PostConstruct
:相當于init-method@PreDestroy
:相當于destroy-method@Service("userService")public class UserServiceImpl implements UserService { @Override public void save() { System.out.println("保存用戶"); } @PostConstruct public void init() { System.out.println("用戶初始化"); } @PreDestroy public void destory() { System.out.println("注銷用戶"); }}通過<context:annotation-config>
的注釋可以看出它的作用是激活 @Required
、@Autowired
、@PostConstruct
、@PreDestroy
、@Resource
等注解。
通過<context:component-scan base-package="xx"/>
的注釋可以看出它除了激活了<context:annotation-config>
中所有的注解,同時還激活了@Component
、@Repository
、@Service
、@Controller
、 @RestController
、@ControllerAdvice
、@Configuration
這些注解。
附上不錯的關于 <context:component-scan>
使用的博文, context:component-scan使用說明
新聞熱點
疑難解答