本文共 2956 字,大约阅读时间需要 9 分钟。
在Spring中,不需要自己创建对象,只需要告诉Spring,哪些类需要创建出对象;在项目启动的时候Spring就会自动创建出该对象。
在Spring中通过注解即可方便地实现注入:
注解分为使用Bean的注解与注册Bean的注解。
使用Bean的注解,即完成属性方法的封装(一般用于修饰‘字段’、‘构造方法’、‘设置方法’),生成要使用的Bean:
@Autowiredprivate UserDao userDao;
@Resource(name = "userServiceImpl")private IUserService userService;
@Autowired@Qualifier("userServiceImpl")private IUserService userService;
注册Bean,一般修饰类,在Spring扫描时实例化对象Bean并放在IoC容器中:
spring: # DataSource Config datasource: driver-class-name: org.h2.Driver schema: classpath:db/schema-h2.sql url: jdbc:h2:file:./dbAccount username: root
@Data@Configuration@ConfigurationProperties("spring.datasource")public class DbSourceConfig { private String driverClassName; private String schema; private String username;}
配置文件中的中划线,对应到类变量时改为驼峰命名即可。
默认情况下,从**<Application启动类>所在包
**的位置,从上往下扫描;若需要扫描的类不在启动类所在的包
或启动类所在包的子包
,则需要在启动类中配置@ComponentScan
注解来添加这些类的包。
package com.example.study;@SpringBootApplication@ComponentScan(basePackages = { "com.other.toScan"})public class StudyApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(StudyApplication.class, args); }}
所有com.example.study
包与其子包中的类会被自动扫描,其他类则需要通过@ComponentScan
来添加。
条件注解可根据不同的条件做不同的事情。
所有条件注解,都是通过扩展Condtion接口实现的:
@FunctionalInterfacepublic interface Condition { boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);}
@Conditional注解,就是利用Condition接口判断条件是否满足,来决定是否初始化并向容器注入Bean。
Spring中提供了一系列相关注解:
@Component@ConditionalOnBean(name="dependedBean")public class ToCreateBean { // ...}
@Component@ConditionalOnClass(DependedClass.class)public class ToCreateBean { // ...}
根据配置参数,来决定是否要创建Bean:
//yml stored: inRedis: false
@Service@ConditionalOnProperty(name = "stored.inRedis", havingValue = "false")public class StoreAcc_LocalDB implements IStoreHandler{ }@Service@ConditionalOnProperty(name = "stored.inRedis", havingValue = "true")public class StoreAcc_Redis implements IStoreHandler{ }// 使用@AutowiredIStoreHandler handler;
转载地址:http://mwilf.baihongyu.com/