java~spring-ioc的使用


spring-ioc的使用

IOC容器在很多框架里都在使用,而在spring里它被應用的最大廣泛,在框架層面
上,很多功能都使用了ioc技術,下面我們看一下ioc的使用方法。

  1. 把服務注冊到ioc容器
  2. 使用屬性注入反射對應類型的實例
  3. 多態情況下,使用名稱反射類型的實例

把服務注冊到ioc容器

  1. @Bean注冊組件

使用@Bean注解進行類型的注冊,默認你的ioc容器里類型為bean的返回值,名稱為bean所有的方法名,與
你的包名稱沒有直接關系,如果你的接口有多種實現,在注冊時可以使用@Bean("lind")這種方式來聲明。

  1. @Component,@Configuration,Service,Repository注冊組件

這幾個注解都是在類上面聲明的,而@Bean是聲明在方法上的,這一點要注意,這幾個注解一般是指對一個
接口的實現,在實現類上加這些注解,例如,一個數據倉儲接口UserRepository,它可以有多種數據持久
化的方式,如SqlUserRepositoryImpl和MongoUserRepositoryImpl,那么在注冊時你需要為他們起
一個別名,如@Repository("Sql-UserRepositoryImpl) SqlUserRepositoryImpl,默認的名稱是
類名,但注意類名首字母為小寫

public interface EmailLogService {
  void send(String email, String message);
}

@Component()
public class EmailLogServiceHttpImpl implements EmailLogService {
  private static final Logger logger = LoggerFactory.getLogger(EmailLogServiceHttpImpl.class);

  @Override
  public void send(String email, String message) {
    Assert.notNull(email, "email must not be null!");
    logger.info("send email:{},message:{}", email, message);
  }
}
@Component("email-socket")
public class EmailLogServiceSocketImpl implements EmailLogService {
  private static final Logger logger = LoggerFactory.getLogger(EmailLogServiceSocketImpl.class);

  @Override
  public void send(String email, String message) {
    Assert.notNull(email, "email must not be null!");
    logger.info("send email2:{},message:{}", email, message);
  }
}
// 看一下調用時的測試代碼
  @Resource(name = "email-socket")
  EmailLogService socketEmail;
  @Autowired
  @Qualifier( "emailLogServiceHttpImpl")
  EmailLogService httpEmail;

  @Test
  public void testIoc2() {
    socketEmail.send("ok", "ok");
  }


  @Test
  public void testIoc1() {
    httpEmail.send("ok", "ok");
  }

在程序中使用bean對象

  1. 使用Resource裝配bean對象
    在通過別名調用bean時,你可以使用@Resource注解來裝配對象

  2. 使用@Autowired裝配bean對象
    也可以使用 @Autowired
    @Qualifier( "emailLogServiceHttpImpl")兩個注解去實現程序中的多態

使用場景

在我們有些相同行為而實現方式不同的場景中,如版本1接口與版本2接口,在get方法實現有所不同,而這
兩個版本都要同時保留,這時我們需要遵守開閉原則,擴展一個新的接口,而在業務上對代碼進行重構,
提取兩個版本相同的方法到基類,自己維護各自獨有的方法,在為它們的bean起個名字,在裝配時,通過
bean的名稱進行裝配即可。

寫個偽代碼:

class Api_version1(){
@Autowired 
@Qualifier("print-version1")
PrintService printService;
}

class Api_version2(){
@Autowired 
@Qualifier("print-version2")
PrintService printService;
}

class BasePrintService{}

interface PrintService{}

@Service("print-version1")
class PrintServiceImplVersion1 extends BasePrintService implements PrintService{}

@Service("print-version2")
class PrintServiceImplVersion2 extends BasePrintService implements PrintService{}

好了,這就是大叔總結的關於spring-ioc的一種東西!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM