装配Bean-复习

简单了解spring装配机制。
Spring 有三种装配机制:xml配置,java配置,隐式的bean发现机制和自动装配。
从两个角度来实现自动化装配:组件扫描(component scanning)自动查找应用上下文的Bean,自动装配(auto wiring)自动查找依赖。

以下正文。

创建bean:
  1. @Component注解,在类上加上@Component注解,注册为可用bean,需要启用组件扫描,创建一个配置类加上@ComponentScan@Configuration,或者是xml配置扫描,<context:component-scan base-package="bean所在包名">。
  2. 测试,测试类需要加载应用上下配置@ContextConfiguration(classes=配置类.class),junit需要用@Runwith。
  3. 设置bean名或者说ID,@Component("xxx")或是@Named("xxx")(java依赖注入)。
  4. @Autowired注解,自动装配,通过构造方法实例化传入bean,this设置bean。还可以在属性方法上使用。
  5. @Bean,创建简单的bean,在方法上加上@Bean注解,接受方法返回对象,注册为应用上下文中的bean,设置id同@Component。
  6. xml创建bean,<bean id="" class="类名"/> 同@Component。

7.构造器注入,<constructor-arg ref="要注入的bean"> 还可以注入多个,通过<list><ref bean=""/></list><set><ref bean=""/></set>,c-命名空间,<bean c:构造器参数名-ref="要注入的bean">。
8.属性注入,<property name="" ref=""/>,p-命名空间<bean p:类名-ref="类名"/>

环境与profile

  1. @Profile注解应用在类上,@Profile("dev"),@Profile("prod"),在xml上<beans profile=""></beans>
  2. 在web.xml设置使用环境

更多内容,不定时更新

评论

暂无评论