Spring 注解

2022-07-07  本文已影响0人  Tinyspot

1. @Annotation

1.1 注解需引入的包

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

2. Bean 配置

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.xxx1")
@ComponentScan("org.example.xxx2")
// 等价
@ComponentScans({
        @ComponentScan("com.example.xxx1"),
        @ComponentScan("com.example.xxx2")
})

2. 常用注解

2.1 @Autowired

2.2 @Resource

2.3 @Component

2.4 @Controller vs @RestController

@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

2.6 其他

3. bean 作用域

image.png

3.1 BeanName

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);
}
上一篇 下一篇

猜你喜欢

热点阅读