0

spring | @Configuration @Bean

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/18/spring18/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

spring | @Configuration @Bean

这两个可以理解为人为主动向 spring IOC 中注册对象。

一般来说,spring IOC 的注册和使用流程如下。

但是,借助 @Configuration @Bean 可以进行人为注册,具体看下面例子。

编写一个接口类

public interface ArticleService {
void listArticle();
}

实现接口类

实现两个接口类。

public class ArticleServiceImpl implements ArticleService {

@Override
public void listArticle() {
System.out.println(1);
}
}
public class ArticleService2Impl implements ArticleService {

@Override
public void listArticle() {
System.out.println(2);
}
}

注意,这两个接口类,都没有用 @component @Repository @Service @Controller 修饰

人为注册 Bean

@Configuration
public class ArtImpl {

@Bean
public ArticleService articleServiceImpl() {
return new ArticleServiceImpl();
}

@Bean
public ArticleService articleService2Impl() {
return new ArticleService2Impl();
}
}

使用 Bean

@RestController
@RequestMapping("/articles")
public class ArticleController {

@Resource(name = "articleServiceImpl")
public ArticleService articleService;

@GetMapping("/hello")
public int listArticle(@RequestParam(value = "id") int id) {
articleService.listArticle();
return id;
}
}

上面的 @Resource(name = "articleServiceImpl") 中的 articleServiceImpl,就是 人为注册 bean 中的第一个 Bean

请我喝杯咖啡吧~

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK