Spring Study-lesson08 使用注解开发-03-16

第一:使用注解开发必须导入AOP的包加载依赖了。spring-webmvc

第二:在使用注解需要导入context约束,增加注解的支持  在beans.xml文件中

第三:@component 

//@component 组件,相当于在配置文件中bean的动作

第四:@属性注入:在setf方法上增加语句@Value(“所赋值”)

@Value("飞剑0316")   // 相当于在xml文件中 property name = "name" value ="飞剑0316" 简单可以用,复杂还是在配置文件中配置
public void setName(String name) {
    this.name = name;
}

第五:衍生的注解

@Component 有几个衍生注解,在web开发中,会按照MVC三层架构分层  相当于四个都是等价的

   - dao 【@Repository】 相当@Component  只是在不同的层衍生不一样的bean

   - service  [@Service] 

   - controller [@Controller]

第六:作用域  @Scope

##注解说明
-@Autowired:自动装配通过类型、名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)
-@Nullable 字段标注了这个注解,说明这个字段可以为null
-@Resource: 自动装配通过名字、类型
-@Component:组件,放在类上,说明这个类被Spring管理了。就是bean
   @Service @Repository (POJO层) @Controller
-@Value("飞剑0316")  属性注解赋值的方法
-@Scope 作用域
@Service
public class UserService {
}
@Controller
public class UserController {
}
@Repository
public class User {
}

 

XML使用于任何场合,维护简单方便

注解:不是自己类使用不了,维护相对比较复杂

最佳实践:XML用来管理bean, 注解只负责属性的注入。 必须让注解生效,必须要开启注解的支持

<!-- 指定要扫码的包,这个包下的注解就会生效    -->
<context:component-scan base-package="com.feijian"/>
<context:annotation-config/>
posted @ 2023-03-16 19:26  Rui2022  阅读(9)  评论(0编辑  收藏  举报