spring中创建bean的方式

一、常见的bean创建方式

(1)基于xml配置bean

(2)使用@Component派生注解

(3)使用@Configuration和@Bean注解

1、常见的使用xml中setter方法创建bean

bean.xml文件中配置bean时,加上<property>标签设置bean所需参数

  <bean id="bookManageDao" class="com.swys.cbgl.dao.BookManageIbatisDao">
              <property name="sqlMapClient" ref="sqlMapClient"/>
  </bean>

2、使用@Component注解创建bean

在spring2.5中开始支持:@Component@Repository@Service@Controller等注解定义bean。

如果你有看过这些注解的源码的话,就会惊奇得发现:其实后三种注解也是@Component

@Component系列注解的出现,给我们带来了极大的便利。我们不需要像以前那样在bean.xml文件中配置bean了,现在只用在类上加Component、Repository、Service、Controller,这四种注解中的任意一种,就能轻松完成bean的定义。

注意,这四种注解在功能上没有特别的区别,不过在业界有个不成文的约定:

  • Controller 一般用在控制层
  • Service 一般用在业务层
  • Repository 一般用在数据层
  • Component 一般用在公共组件上

@RestController
@RequestMapping("/inventory/instock")
public class InstockController extends BaseController {
}

@Service
@Slf4j
public class StockCancelServiceImpl extends BaseServiceImpl<StockCancel, StockCancelDao> implements StockCancelService {

在springBoot中,在启动类上面添加@ComponentScan注解

@ComponentScan()
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);
    }
}

此外,除了上述四种@Component注解之外,springboot还增加了@RestController注解,它是一种特殊的@Controller注解,所以也是@Component注解。

@RestController还支持@ResponseBody注解的功能,即将接口响应数据的格式自动转换成json。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

@Component系列注解它目前是我们日常工作中最多的定义bean的方式。

3、JavaConfig,@Configuration创建bean

@Component系列注解虽说使用起来非常方便,但是bean的创建过程完全交给spring容器来完成,我们没办法自己控制。

spring从3.0以后,开始支持JavaConfig的方式定义bean。它可以看做spring的配置文件,但并非真正的配置文件,我们需要通过编码java代码的方式创建bean。例如

/**
 * bean配置类
 **/
@Configuration
public class BeanConfig {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        // 线程池数量
        executor.setPoolSize(Runtime.getRuntime().availableProcessors());
        //设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("charge-task-Executor-");
        //用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}

在JavaConfig类上加@Configuration注解,相当于配置了<beans>标签。而在方法上加@Bean注解,相当于配置了<bean>标签。

springboot还引入了一些列的@Conditional注解,用来控制bean的创建。

例如:

@ConditionalOnClass注解的功能是当项目中存在Country类时,才实例化Person类。换句话说就是,如果项目中不存在Country类,就不实例化Person类。

这个功能非常有用,相当于一个开关控制着Person类,只有满足一定条件才能实例化。

spring中使用比较多的Conditional还有:

  • ConditionalOnBean
  • ConditionalOnProperty
  • ConditionalOnMissingClass
  • ConditionalOnMissingBean
  • ConditionalOnWebApplication

4、 Import注解 

@Configuration和@Bean相结合的方式,我们可以通过代码定义bean。但这种方式有一定的局限性,它只能创建该类中定义的bean实例,不能创建其他类的bean实例,如果我们想创建其他类的bean实例该怎么办呢?

这时可以使用@Import注解导入。

spring4.2之后@Import注解可以实例化普通类的bean实例

接下来使用@Import注解导入

@Import({Role.class, User.class})
@Configuration
public class MyConfig {
}


@Import({Role.class, User.class}) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args); } }
学有所思,思有所成。
原文地址:https://www.cnblogs.com/lqh969696/p/15033602.html