温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

好程序员Java学习路线分享Spring创建Bean的3种方式

发布时间:2020-08-08 08:17:31 来源:网络 阅读:156 作者:wx5d42865f47214 栏目:编程语言

好程序员Java学习路线分享Spring创建Bean的3种方式,本文讲解了在Spring 应用中创建Bean的多种方式,包括自动创建,以及手动创建注入方式,实际开发中可以根据业务场景选择合适的方案。

方式1:
使用Spring XML方式配置,该方式用于在纯Spring 应用中,适用于简单的小应用,当应用变得复杂,将会导致XMl配置文件膨胀 ,不利于对象管理。

<bean id="xxxx" class="xxxx.xxxx"/>

方式2:

使用@Component,@Service,@Controler,@Repository注解

这几个注解都是同样的功能,被注解的类将会被Spring 容器创建单例对象。

@Component : 侧重于通用的Bean类

@Service:标识该类用于业务逻辑

@Controler:标识该类为Spring MVC的控制器类

@Repository: 标识该类是一个实体类,只有属性和Setter,Getter

1

2

3

@Component

public class User{

}

当用于Spring Boot应用时,被注解的类必须在启动类的根路径或者子路径下,否则不会生效。

如果不在,可以使用@ComponentScan标注扫描的路径。

spring xml 也有相关的标签<component-scan />

1

2

3

4

5

6

@ComponentScan(value={"com.microblog.blog","com.microblog.common"})

public class MicroblogBlogApplication {

public static void main(String args[]){

SpringApplication.run(MicroblogBlogApplication.class,args);

}

}

方式3:

使用@Bean注解,这种方式用在Spring Boot 应用中。

@Configuration 标识这是一个Spring Boot 配置类,其将会扫描该类中是否存在@Bean 注解的方法,比如如下代码,将会创建User对象并放入容器中。

@ConditionalOnBean 用于判断存在某个Bean时才会创建User Bean.

这里创建的Bean名称默认为方法的名称user。也可以@Bean("xxxx")定义。

1

2

3

4

5

6

7

8

@Configuration

public class UserConfiguration{

@Bean

@ConditionalOnBean(Location.class)

public User user(){

return new User();

}

}

Spring boot 还为我们提供了更多类似的注解。


也和方式2一样,也会存在扫描路径的问题,除了以上的解决方式,还有使用Spring boot starter 的解决方式

在resources下创建如下文件。META-INF/spring.factories.

Spring Boot 在启动的时候将会扫描该文件,从何获取到配置类UserConfiguration。

spring.factories.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.log.config.UserConfiguration

如果不成功,请引入该依赖

1

2

3

4

5

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-configuration-processor</artifactId>

<optional>true</optional>

</dependency>

这个方式也是创建SpringBoot-starter的方式。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI