AppServiceConfig.java 等等。我们需要在用于指定配置信息的类上加上 @Configuration 注解,以明确指出该类是 Bean 配置的信息源。并且 Spring 对标注 Configuration 的类有如下要求:
配置类不能是 final 的; 配置类不能是本地化的,亦即不能将配置类定义在其他类的方法内部; 配置类必须有一个无参构造函数。
AnnotationConfigApplicationContext 将配置类中标注了 @Bean 的方法的返回值识别为 Spring Bean,并注册到容器中,受 IoC 容器管理。@Bean 的作用等价于 XML 配置中的 <bean/> 标签。示例如下:
@Configuration public class BookStoreDaoConfig{ @Bean public UserDao userDao(){ return new UserDaoImpl();} @Bean public BookDao
bookDao(){return new BookDaoImpl();} }
Spring 在解析到以上文件时,将识别出标注 @Bean 的所有方法,执行之,并将方法的返回值 ( 这里是 UserDaoImpl 和 BookDaoImpl 对象 ) 注册到 IoC 容器中。默认情况下,Bean 的名字即为方法名。因此,与以上配置等价的 XML 配置如下:
<bean id=”userDao” class=”bookstore.dao.UserDaoImpl”/> <bean id=”bookDao” class=”bookstore.dao.BookDaoImpl”/>
@Bean 具有以下四个属性:
name -- 指定一个或者多个 Bean 的名字。这等价于 XML 配置中 <bean> 的 name 属性。 initMethod -- 容器在初始化完 Bean 之后,会调用该属性指定的方法。这等价于 XML 配置中 <bean> 的 init-method 属性。 destroyMethod -- 该属性与 initMethod 功能相似,在容器销毁 Bean 之前,会调用该属性指定的方法。这等价于 XML 配置中 <bean> 的 destroy-method 属性。 autowire -- 指定 Bean 属性的自动装配策略,取值是 Autowire 类型的三个静态属性。
Autowire.BY_NAME,Autowire.BY_TYPE,Autowire.NO。与 XML 配置中的 autowire 属性的取值相比,这里少了 constructor,这是因为 constructor 在这里已经没有意义了。
@Bean 没有直接提供指定作用域的属性,可以通过 @Scope 来实现该功能,关于 @Scope 的用法已在上文列举。
下面讲解基于注解的容器初始化。AnnotationConfigApplicationContext 提供了三个构造函数用于初始化容器。
AnnotationConfigApplicationContext():该构造函数初始化一个空容器,容器不包含任何 Bean 信息,需要在稍后通过调用其 register() 方法注册配置类,并调用 refresh() 方法刷新容器。 AnnotationConfigApplicationContext(Class<?>... annotatedClasses):这是最常用的构造函数,通过将涉及到的配置类传递给该构造函数,以实现将相应配置类中的 Bean 自动注册到容器中。 AnnotationConfigApplicationContext(String... basePackages):该构造函数会自动扫描以
给定的包及其子包下的所有类,并自动识别所有的 Spring Bean,将其注册到容器中。它不但识别标注 @Configuration 的配置类并正确解析,而且同样能识别使用 @Repository、@Service、
@Controller、@Component 标注的类。
详解Spring 3.0 基于 Annotation 的依赖注入实现_计算机软件及应用_IT/计算机_专业资料。详解 Spring 3.0 基于 Annotation 的依赖注入实现...
Spring+3.0+基于+Annotation+的依赖注入实现Spring+3.0+基于+Annotation+的依赖注入实现隐藏>> 中文 登录 (或注册) 技术主题 软件 下载 社区 技术 讲座 搜索 ...
详解Spring 3.0 基于 Annotation 的依赖 注入实现使用 @Repository、@Service、@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了...
Spring 3.0 注解注入详解_计算机软件及应用_IT/计算机_专业资料。Spring 3.0....spring\.annotation\.web\..*
Spring 3.0 注解注入详解_计算机软件及应用_IT/计算机_专业资料。Spring 3.0...annotation-config /> beans> 将隐式地向 Spring 容器注册了 Autowired...
基于Annotation的Spring AOP日志处理的设计与实现_计算机软件及应用_IT/计算机_专业资料。Value Engineering ·207· 基于 Annotation 的 Spring AOP 日志处理的设计...
Spring3 的基于注解实现 Bean 依赖注入支持如下三种注解: ? ? Spring 自带依赖...13. <context:annotation-config/> xmlns:xsi="http://www.w3.org/2001/...
注解: 在 spring的配置文件里面只需要加上<context:annotation-config/>和<context:component-scanbase-package="需要实现注入的类所在包"/>,可以使用base-package...
我们需要直接或间接地实现 org.springframework.web....以完成Bean创建和自动依赖注入的功能 --> <context...AnnotationMethodHandlerAdapter"/> <!-- ③:对模型...
热门文档