1、獲取spring容器java
一、Spring中,管理XML配置Bean定義的容器:ApplicationContext context = new ClassPathXmlApplicationContext("application.xml")。經過容器能夠獲取bean,context .getBean("beanId")。web
二、Spring中,管理註解Bean定義的容器有兩個:AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContex。這兩個類是專門處理Spring註解方式配置的容器,直
接依賴於註解做爲容器配置信息來源的IOC容器。AnnotationConfigWebApplicationContext是AnnotationConfigApplicationContext的web版本,二者的用法以及對註解的處理方式幾乎。spring
2、bean配置與管理app
2.一、spring xml配置文件:配置beanspa
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="duke" class="com.springinaction.springidol.Juggler" > <!-- 經過構造方法設置屬性值 --> <constructor-arg value="15"></constructor-arg> </bean> </beans>
2.二、從Spring3.0,@Configuration用於定義配置類。配置bean至關於一個spring xml配置文件code
package com.dxz.demo.configuration; import org.springframework.context.annotation.Configuration; @Configuration public class TestConfiguration {
@Bean public Juggler duke() { return new com.springinaction.springidol.Juggler(); } }
3、自定義註解xml
import java.lang.annotation.*; @Documented @Inherited @Target({ ElementType.FIELD, ElementType.METHOD ,ElementType.TYPE_USE,ElementType.ANNOTATION_TYPE,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface RedisHandel { String key() default ""; String keyField() default "username"; }
4、獲取自定義註解blog
4.一、獲取指定註解全部的 Beanget
Map<String,Object> objectMap = applicationContext.getBeansWithAnnotation(Service.class);
4.二、獲取指定註解全部的 Bean 的名字it
String[] beanNames = applicationContext.getBeanNamesForAnnotation(Service.class);