spring注解中的@Autowired和@Component基本作用
2015-11-01 23:38
393 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012371521/article/details/84747701
1.我们在初次写spring的demo程序的时候,一定会觉得很繁琐,我要用一个类,直接new不就行了么,搞这么麻烦?
但是当我们用的稍微多了些的时候,就会发现,当我们需要的对象很多的时候,管理这些对象很复杂,很麻烦!!
所以,spring框架给了我们很好的方法去简化操作,@Autowired和@Component简直就是一对兄弟搭档
2. @Autowired
作用:@Autowired表示被修饰的类需要注入对象,spring会扫描所有被@Autowired标注的类,然后根据 类型 在ioc容器中找到匹配的类注入。
示例代码:
@Autowired public class Car(Brand benz) { this.brand=benz; }
Car这个类被标注了,那么spring扫描到之后,发现需要Brand这个类的实例对象,那么spring会去ioc容器中找到类型匹配的对象注入。基本流程就是这样的,至于其他更复杂的问题,比如同一个类型的类有多个不同的bean,注入哪个,请百度吧。 当然,实现这种功能需要在ApplicationContext.xml中进行配置。
3. @component
作用:把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
虽然有了@Autowired,但是我们还是要写一堆bean的配置文件,相当麻烦,而@Component就是告诉spring,我是pojo类,把我注册到容器中吧,spring会自动提取相关信息。那么我们就不用写麻烦的xml配置文件了,yeah!
当然,实现这种功能需要在ApplicationContext.xml中进行配置。
4.spring有2种注册bean的方式,一种是xml文件配置,另外一个是通过注解完全去除xml文件中的bean配置,
找了一天,发现一篇很好的文章
相关文章推荐
- spring注解中的@Autowired和@Component基本作用
- Spring @Autowired、@Resource、@Required、@Component、@Repository、@Service、@Controller注解的用法和作用
- Spring注解标签详解@Autowired @Qualifier @Component
- Spring @Autowired,@Resource,@Required注解的用法和作用
- Spring注解@Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier 解析
- Java框架spring 学习笔记(九):Spring的bean管理(@Required、@Component、@Autowired、@Resource注解)
- spring mvc 注解基本配置(@resource,@autowired,@Component...)
- spring 的@Autowired注解的作用
- spring 常用注解关系(@Component,@Controller,@Service,@Repository,@Autowired,@Resource),@Qualifier
- Spring注解@Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier、@scope
- spring mvc 注解基本配置(@resource,@autowired,@Component...)
- SpringBoot——@Autowired注解的作用
- Spring注解@Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier、@scope
- @Resource或者@Autowired作用/Spring中@Autowired注解、@Resource注解的区别
- SpringMVC 基本注解[@Resource,@Autowired,@Component]
- spring mvc 注解基本配置(@resource,@autowired,@Component...)
- Spring注解@Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier 解析
- Spring @Autowired,@Resource,@Required注解的用法和作用
- Spring @Resource @Autowired @Component常用注解
- Spring注解@Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier 解析[转]