package com.xxx.product.web;
/**
* @program: product
* @description
* @create: 2021-05-12 17:28
**/
public interface OrderService {
boolean deleteOrderById(Long orderId);
}
package com.xxx.product.web;
import org.springframework.stereotype.Service;
/**
* @program: product
* @description
* @create: 2021-05-12 17:28
**/
@Service
public class OrderServiceImpl implements OrderService {
@Override
public boolean deleteOrderById(Long orderId) {
return false;
}
}
参看上面的代码,问题:
1. OrderService 的bean对象在ioc 容器中是否只有一个?
2. 如果不止一个,多个的话, 这多个 OrderService 对象是同一个对象吗?
3. 如果存在是多个对象,如何往ioc容器中放置多个OrderService 对象?
都说spring ioc容器启动的时候,默认创建的bean对象都是单例的,假如你不配置的话,单例对象,和我们了解的单例模式有点像,但是这两者是没有绝对的关联关系。
解答:
1. 上面的OrderService 对象在ioc容器中是只有一个,因为我们只创建了一个 OrderService 对象,这个对象是spring 初始化的时候根据@Service注解 生成创建的。
但是我们可以创建多个 OrderService 对象然后交由spring帮我们管理,这样在ioc容器中就有多个 OrderService bean对象了。至于怎么将普通的对象交由spring 管理 ,可以看我博客中的另外一篇文章。
2. ioc容器中可以有多个 OrderService对象,并且这些bean对象是不同的对象,和我们了解的单例模式不是一个概念,思想上不要先入为主,看到单例就和单例模式匹配了。
3. @Bean 注解就是其中的一种方式,通过这个注解可以创建多个 OrderService bean对象,这样在 ioc容器中就有 多个 OrderService bean对象了, 示例:
package com.xxx.product.web.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @program: product
* @description
* @create: 2021-05-12 18:04
**/
@Configuration
public class MyConfig {
/**
* ioc 容器中beanname 是'orderService'
* @return
*/
@Bean
public OrderService orderService(){
OrderService orderService = new OrderServiceImpl();
return orderService;
}
/**
* ioc 容器中beanname 是'orderService2'
* @return
*/
@Bean
public OrderService orderService2(){
OrderService orderService = new OrderServiceImpl();
return orderService;
}
/**
* ioc 容器中beanname 是'orderService3'
* @return
*/
@Bean
public OrderService orderService3(){
OrderService orderService = new OrderServiceImpl();
return orderService;
}
}
通过相应的 beanname就能从 ioc容器中获取到 对应的bean。 你可以测试下结果。