美文网首页
8 使用注解开发

8 使用注解开发

作者: Messix_1102 | 来源:发表于2023-03-29 09:10 被阅读0次

在Spring4 之后,要使用注解开发,必须要保证aop包的导入


maven截图

使用注解要导入context约束,增加注解的支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解的支持-->
    <context:annotation-config/>

</beans>

1 bean
2 属性如何注入

package com.hunter.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

// 等价于<bean id="user" class="com.hunter.pojo.User"></bean>
@Component // 组件
public class User {
    // 等价于<property name="name" value="hunter"></property>
    // 也可以放到set方法上面
    @Value("hunter")
    public String name;
}

3 衍生的注解

@Component 有几个衍生注解,在我们的web开发中,会按照mvc三层架构分层!

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】
    这四个注解功能是一样的,都是将被注解的类注入到Spring 容器中,装配bean

4 自动装配

  • @Autowired: 自动装配通过类型、名字
    如果 @Autowired 不能唯一装配上属性,则需要通过 @Qualifier(value=XXX) 指定
  • @Resource: 自动装配通过名字、类型
    如果 @Resource 不能唯一装配上属性,则需要通过 @Resource(name=XXX) 指定
  • @Nullable: 字段标记了这个注解,说明这个字段可以为null

5 作用域

@Scope("singleton")
public class User {
...

6 小结
xml 与注解:

  • xml 更加万能,适用于任何场合,维护更加方便!
  • 注解不是自己的类使用不了,维护相对复杂

最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题,必须要注解生效就要开启注解支持
    <context:component-scan base-package="com.hunter"/>
    <context:annotation-config/>

相关文章

  • 8、使用注解开发

    8.1:面向接口编程 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程 ...

  • Spring讲解(四)

    Spring 中使用注解注入 注解:就是一个类,使用 @ 注解名称。实际开发中:使用注解取代 xml 配置文件。 ...

  • SSM框架注解

    Spring注解 @Configuration:表示使用注解的格式开发 必须定义 @Bean:自己创建对象使用 @...

  • mybatis注解开发

    1.Mybaits常用注解说明 1.1 使用Mybatis注解实现基本CRUD 1.2 使用注解方式开发持久层接口...

  • 105、【JavaEE】【Mybatis】注解开发

    1、概述 使用注解开发,就不需创建相应的映射配置文件。 注解开发、映射配置文件开发各有优劣。注解开发和 XML 配...

  • Spring注解开发

    使用注解开发spring(重点) 在spring4之后,使用注解开发必须和AOP一同使用和mybatis一样,只建...

  • MyBatis之使用注解开发

    六、使用注解开发 目录:面向接口编程、使用注解开发、CRUD、Lombok 1.面向接口编程 之前都学过面向对象编...

  • Kotlin注解(2)自定义注解

    声明注解案例:使用元注解注解目标声明案例:读取运行时注解信息   与基本注解不同,在一般的应用开发中不会直接使用元...

  • SpringMVC开发常见注解

    springMVC开发中使用了许多注解,不仅方便开发,也使代码更加简洁。 常用的注解有: @RequestMapp...

  • Mybatis 注解1.0

    8、使用注解开发 8.1、面向接口编程 - 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我...

网友评论

      本文标题:8 使用注解开发

      本文链接:https://www.haomeiwen.com/subject/nbazqrtx.html