spring多例注入失效

2021-09-01 03:04:46 字數 859 閱讀 1814

springcloud中繼承hystrixcommand類只能執行一次,而我寫的流程為:乙個request-->controller-->hystrixcommand繼承的類。為了讓繼承hystrixcommand的類的物件每次從容器中拿到的對像都是最新new出來的,在上面加上了@scope("prototype"),但拿到的仍是上一次new出來的物件。經過排查,需要在controller和hystrixcommand繼承的類上新增@scope("prototype")才得以解決。

@restcontroller

@scope("prototype")

public class deptcontroller

@component

@scope("prototype")

public class depthystrix extends hystrixcommand

public depthystrix()

@autowired

private deptservice service = null;

@override

protected dept getfallback()

@override

protected dept run() throws exception

return dept;

}}

結論:如果只在depthystrix上加上prototype,那每從deptcontroller中拿到的仍是之前的depthystrix物件,原因就是deptcontroller就是同乙個物件,它裡面的物件在一開始就注入好了,不會從容器中拿取,當然就與depthystrix是否是單例毫無關係。

Spring使用註解方式注入多例的方式

目前spring netty的開發方式這麼火熱,想把netty註冊成spring元件就一定得用多例的方式,我不由得想吐槽明明這麼常見的需求網上相關部落格都少的很,這裡給出spring使用註解注入多例的方式 在需要多例呼叫的類上加 scope prototype 在進行注入時,不能直接使用 autow...

Spring自動注入單例和多例如何選擇

spring中bean的scope屬性,有如下5種型別 singleton 表示在spring容器中的單例,通過spring容器獲得該bean時總是返回唯一的例項 prototype表示每次獲得bean都會生成乙個新的物件 request表示在一次http請求內有效 只適用於web應用 sessio...

spring 單例與多例

id student class com.ly.entity.student init method init destroy method destroy scope singleton bean scope prototype 為多例 預設單例模式 singleton 單例模式 框架啟動時,就例...