【查漏补缺】普通类中获取有注解的类

通过实现ApplicationContextAware接口获取

 1 @Component
 2 public class ApplicationContextHolder implements ApplicationContextAware {
 3     private static ApplicationContext context;
 4 
 5     @Override
 6     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 7         context = applicationContext;   
 8     }
 9 
10     public static ApplicationContext getContext() {
11         return context;
12     }
13 }

@Component 把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>

使用注解来构造IoC容器

用注解来向Spring容器注册Bean,需要在applicationContext.xml中注册<context:component-scan base-package=""/>

表明该包及其子包中,如果某个类的头上有特定的注解【@Component/@Repository/@Service/@Controller】就会将这个对象作为Bean注解进Spring容器。也可以在context:component-scan base-package="">中指定多个包。

@Component

所有受Spring管理组件的通用形式,@Component注解可以放在类的头上

@Controller

注意:如果@Controller不指定名称,那么默认bean的名字为这个类的类名首字母小写

@Service

注意:在Action声明的“userService”变量的类型必须是“UserServiceImpl”或者是其父类“UserService”,否则由于类型不一致而无法注入

@Repository

对应数据访问层的Bean

猜你喜欢

转载自www.cnblogs.com/dream-to-pku/p/9358868.html