首页 > 其他分享 >【Spring】spring中创建bean的方式

【Spring】spring中创建bean的方式

时间:2023-02-27 19:35:38浏览次数:43  
标签:创建 Spring Component bean spring 注解 class

(181条消息) spring中创建bean的方式_清华大咖的博客-CSDN博客

 

(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@Slf4jpublic 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})@Configurationpublic 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);
}
}

 

标签:创建,Spring,Component,bean,spring,注解,class
From: https://www.cnblogs.com/cuipengchong/p/17161571.html

相关文章

  • 【Spring】@Import注解
    (181条消息)@Import注解_ZmyCoder的博客-CSDN博客_@import 1、@Import注解须知@Import只能用在类上,@Import通过快速导入的方式实现把实例加入spring的IOC容器中......
  • springboot中redis使用和工具
    application.properties#Redis相关配置spring.data.redis.host=localhost#端口spring.data.redis.port=6379#reids数据库索引spring.data.redis.database=0Red......
  • springboot脱包部署
    <plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration>......
  • spring aop切面说明
    execution:处理JoinPoint的类型,例如call、execution(*android.app.Activity.on**(..)):这个是最重要的表达式,第一个*表示返回值,*表示返回值为任意类型,后面这个就是典型的......
  • springboot条件注册Condition注解
    环境识别importorg.springframework.context.annotation.Condition;importorg.springframework.context.annotation.ConditionContext;importorg.springframework.c......
  • 基于SpringBoot WebMagic爬虫爬取大乐透双色球
    大乐透网页地址:https://kjh.55128.cn/dlt-history-360.htm双色球网页地址:https://kjh.55128.cn/ssq-history-120.htm 注:程序仅用于个人兴趣爱好,不得用于商业行为,本......
  • SpringBoot项目打包部署
    转载自:https://blog.csdn.net/yw_2022/article/details/122649955========= SpringBoot项目打包在linux服务器中运行:jar类型项目会打成jar包:jar类型项目使用SpringBoo......
  • springcloud集成nacos(详细)
    一、什么是nacos官方:一个更易于构建云原生应用的动态服务发现、服务配置、和服务管理平台理解:注册中心(如:服务地址注册进去根据名称调用)、配置中心(如:每个服务yaml中的配置......
  • spring jpa 使用
    SpringBoot集成jpa网上有很对jpa的介绍,但是都不是很全,这边根据公司的实际使用情况进行的总结。JPA、Hibernate、Springdatajpa之间的关系主要参考https://my.oschina.ne......
  • Spring学习笔记
    1.Spring作为轻量级框架的两大核心:IOC、AOP、事务处理(基于AOP)。2.经过学习要会什么?  核心概念IOC、DI >>>>整合mybatis>>>>AOP概念及操作>>>>事务实用开发3.架构......