Spring--依赖注入

1 基于注解
在具体的类上添加 @Repository、@Service、@Controller 和 @Component 将类标识为 Bean,Spring将会自动创建BeanDefination对象,并注册到Application中。在SpringMVC中的配置文件忠添加context:component-scan/ ,启动Bean的自动扫描。
各个注解说明如下:
@Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
@Service 通常作用在业务层,但是目前该功能与 @Component 相同。
@Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
@Repository 用于数据访问层。

2 使用注解对类中的方法的返回值进行Bean的声明。
对声明的类有如下要求:
配置类不能是 final 的;
配置类不能是本地化的,亦即不能将配置类定义在其他类的方法内部;
配置类必须有一个无参构造函数。
AnnotitionConfigApplicationContext配置忠的返回识别为Spring Bean,并且注册到IOC中进行管理。
如下两种方式等价。
在类中使用Configuration注解

@Configuration
public class BookStoreDaoConfig{
   @Bean
   public UserDao userDao(){ return new UserDaoImpl();}
   @Bean
   public BookDao bookDao(){return new BookDaoImpl();}
}

在配置文件中:

<bean id=”userDao” class=”bookstore.dao.UserDaoImpl”/>
<bean id=”bookDao” class=”bookstore.dao.BookDaoImpl”/>

@Conditional注解value值配置根据当前环境决定是否注入Bean到Spring容器中。

/**
 * @Author: ShipTang
 * @Description: 只有当前环境是linux环境才注册bean
 * @Date: 2021/6/1 10:04
 */
@Slf4j
public class SystemCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean isWindows = SystemUtils.currentIsWindows();
        if (isWindows) {
            log.info("当前环境是windows,不注册该bean:{}", this.getClassOrMethodName(metadata));
            return false;
        } else {
            log.info("当前环境是linux,注册该bean:{}", this.getClassOrMethodName(metadata));
            return true;
        }
    }

    private String getClassOrMethodName(AnnotatedTypeMetadata metadata) {
        if (metadata instanceof ClassMetadata) {
            ClassMetadata classMetadata = (ClassMetadata) metadata;
            return classMetadata.getClassName();
        }
        MethodMetadata methodMetadata = (MethodMetadata) metadata;
        return methodMetadata.getDeclaringClassName() + "#" + methodMetadata.getMethodName();
    }
}
@Conditional(value = SystemCondition.class)
@Component
@SuppressWarnings("unchecked")
public class PullDataTask {
}

Autowrite注入规则
先根据变量类型注入,如果一个变量存在多个实现类,那么会出现异常,
1 可以将变量名设置为Spring中Bean的id。
2 使用Qualifier定义需要注入的Bean的id。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值