Spring Bean 声明

1. 依赖包

org.springframeworkspring-context5.3.19

2. 常用注解

2.1 @Component

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

2.2 @Configuration

  • 表示配置类,可包含多个@Bean注解
@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }

    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }
}

2.3 @Controller, @RestController

  • @RestController 返回的是 JSON 格式
  • @Controller 返回html页面
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}
@Controller
@RequestMapping("/web")
public class NginxController {
    @RequestMapping("/index")
    public String index() {
        System.out.println("index");
        return "index";
    }
}

对应的htm文件 resources/templates/index.html

3. 其他

3.1 延迟加载 @Lazy

在@Component、@Service、@Repository或@Controller等注解上添加@Lazy注解来实现懒加载

@Service
@Lazy
public class LazyService {
    // ...
}

3.2 默认候选者 @Primary

  • 指定优先使用哪一个bean

示例:接口 MyService 有两个实现类

public interface MyService {
}

@Component
public class DefaultService implements MyService {
    // ...
}

@Component
@Primary
public class PrimaryService implements MyService {
    // ...
}
@Component
public class Demo {
    @Resource
    private MyService myService;
}

PrimaryService 被 @Primary 注解标记,当其他组件需要注入MyService类型的依赖而未明确指定Bean名称时,Spring会自动注入 PrimaryService

注意:@Primary只是在自动注入时提供了一种选择默认Bean的方式,如果有明确的Bean名称引用或者通过Java配置中的@Qualifier注解指定了特定Bean,则@Primary不会起作用

3.3 @DependsOn

  • @DependsOn注解用于指定一个或多个Bean依赖于其他Bean
  • 用来解决 Bean 之间的初始化顺序问题
@Service
@DependsOn("myDependencyService")
public class MyService {
    @Resource
    private final DependencyService dependencyService;
}

【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容