美文网首页
Spring 注解

Spring 注解

作者: Tinyspot | 来源:发表于2022-07-07 07:44 被阅读0次

1. @Annotation

  • 注入模型:byType, byName
  • 常用注解
    • @Component
    • @Autowired
    • @ComponentScan("package.name")
    • @Configuration
    • @Controller, @RestController
    • @Service
    • @DependsOn

1.1 注解需引入的包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.19</version>
</dependency>

2. Bean 配置

  • Java-based Container Configuration
  • @Configuration equivalent beans.xml
  • @Bean equivalent <bean />
  • @Bean用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
User user = (User) context.getBean("queryUser");
@Configuration
@ComponentScan("org.xxx.xxx")
@Import(CustomConfig.class)
@ImportResource("classpath:beans.xml")
@PropertySource("classpath:config/config.properties")
public class UserConfig {
     // @Bean作用于方法; 若不指定对象名,默认方法名是 id
    @Bean("user")
    public User updateUser() {
        return new User("Tinyspot", 12);
    }
}

@Configuration
public class CustomConfig {
    @Bean
    public User query() {
        return new User("yuan", 25);
    }
}

1.1 @ComponentScan

  • @ComponentScan("org.example")
  • @ComponentScan({"org.example.xxx1", "org.example.xxx2"}) 扫描多包
  • 存在多个@ComponentScan时,可以使用 @ComponentScans 将这些@ComponentScan 放在里面统一管理
@ComponentScan("org.example.xxx1")
@ComponentScan("org.example.xxx2")
// 等价
@ComponentScans({
        @ComponentScan("com.example.xxx1"),
        @ComponentScan("com.example.xxx2")
})

2. 常用注解

2.1 @Autowired

  • 是 Spring 的自动装配,根据类型进行自动装配的
  • 通过 byType 注入
  • 指定名称 @Qualifier,@Autowired + @Qualifier("beanName") ,指定唯一的 bean 对象
  • @Autowired(required = false) // 说明对象可以为 null

2.2 @Resource

  • 是 Java 的自动装配,默认 byName,找不到再byType
  • 也可以加 @Resource(name="beanName")

2.3 @Component

  • @Component 等价与 <bean />,属性上可加 @Value("hello")
  • @Component 将对象交给 IOC 容器进行实例化
  • @Component 衍生注解
    • Dao - @Repository
    • Service - @Service
    • Controller - @Controller

2.4 @Controller vs @RestController

  • @RestController 返回的是 JSON 格式
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

示例

@Controller // 要返回 html页面
@RequestMapping("/nginx")
public class NginxController {
    @RequestMapping("/index")
    public String index() {
        System.out.println("index");
        return "index";
    }
}

resources/templates/index.html

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.5 @PropertySource

  • 引入外部的配置文件 .properties

2.6 其他

  • @Primary来指定优先使用哪一个bean
  • 回调函数:当Bean被容器初始化后,会调用 @PostConstruct;在容器被销毁之前,会调用 @PreDestory
  • @Nullable // 可以为 null

3. bean 作用域

image.png

3.1 BeanName

  • @Service("beanName") 可以指定 Bean 名称
  • AnnotationBeanNameGenerator#generateBeanName value 指定了名称就直接用,否则 java.beans.Introspector#decapitalize
public static String decapitalize(String name) {
    if (name == null || name.length() == 0) {
        return name;
    }
  // 如果发现类的前两个字符都是大写,则直接返回类名
    if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
            Character.isUpperCase(name.charAt(0))){
        return name;
    }
  // 将类名的第一个字母转成小写,然后返回
    char chars[] = name.toCharArray();
    chars[0] = Character.toLowerCase(chars[0]);
    return new String(chars);
}

相关文章

网友评论

      本文标题:Spring 注解

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