Coldfusion 为什么依赖项注入在CF factory对象中失败?
我得到这个错误 变量中未定义元素实例 我看不出错误的原因 这是我的工厂Coldfusion 为什么依赖项注入在CF factory对象中失败?,coldfusion,dependency-injection,Coldfusion,Dependency Injection,我得到这个错误 变量中未定义元素实例 我看不出错误的原因 这是我的工厂 <cfcomponent output="true" displayname="ObjectFactory"> <cffunction name="init" access="public" output="true" returntype="ObjectFactory"> <cfset variables.instance = structNew() /> <cfret
<cfcomponent output="true" displayname="ObjectFactory">
<cffunction name="init" access="public" output="true" returntype="ObjectFactory">
<cfset variables.instance = structNew() />
<cfreturn this />
</cffunction>
<cffunction name="createObj" access="public" output="false" returntype="any">
<cfargument name="objName" type="string" required="true" />
<cfswitch expression="#arguments.objName#">
<cfcase value="abstractCollection">
<cfreturn createObject('component',"AbstractCollection").init() />
<cfbreak />
</cfcase>
<cfcase value="assignmentCollection">
<cfreturn createObject('component',"AssignmentCollection").init() />
<cfbreak />
</cfcase>
<cfcase value="salesmanBean">
<cfreturn createObject('component',"SalesmanBean").init(
salesmanHasThisDecorations = this.getInstance("assignmentCollection")) />
<cfbreak />
</cfcase>
</cfswitch>
</cffunction>
<cffunction name="getInstance" access="public" output="false" returntype="any">
<cfargument name="objName" type="string" required="true" />
<!--- Error occurs in the line below --->
<cfif not structKeyExists(variables.instance, arguments.objName)>
<cfset variables.instance[arguments.objName] = this.createObj(arguments.objName) />
</cfif>
<cfreturn variables.instance[arguments.objName] />
</cffunction>
</cfcomponent>
请确保在实例化ObjectFactory时调用init()
<cfset objectFactory = CreateObject("component","ObjectFactory").init()>
仅供参考,init()
和
应具有output='false'
仅供参考,您应该在不使用“this.”的情况下调用自己的函数,因为如果出于某种原因该函数后来声明为private,它将不会在“this”范围内找到它。请确保在实例化ObjectFactory时调用init()
<cfset objectFactory = CreateObject("component","ObjectFactory").init()>
仅供参考,init()
和
应具有output='false'
仅供参考,您应该在不使用“this.”的情况下调用自己的函数,因为如果出于某种原因该函数后来被声明为private,它将不会在“this”范围内找到它。同意您可能不会调用.init(),因此在访问它之前不要创建变量 您还可能希望在init()之外初始化(创建)变量作用域变量。init()应该更多地用于将值传递到内部CFC作用域(VARIABLES作用域),而不是在其中创建变量
<cfcomponent displayname="ObjectFactory">
<cfset variables.instance = structNew() />
<cffunction name="init" access="public" returntype="ObjectFactory">
<cfargument name="name" required="yes" type="string">
<cfset variables.instance.name = arguments.name>
<cfreturn this />
</cffunction>
...
...
同意您可能没有调用.init(),因此在访问变量之前没有创建该变量
您还可能希望在init()之外初始化(创建)变量作用域变量。init()应该更多地用于将值传递到内部CFC作用域(VARIABLES作用域),而不是在其中创建变量
<cfcomponent displayname="ObjectFactory">
<cfset variables.instance = structNew() />
<cffunction name="init" access="public" returntype="ObjectFactory">
<cfargument name="name" required="yes" type="string">
<cfset variables.instance.name = arguments.name>
<cfreturn this />
</cffunction>
...
...
我这样做解决了问题:我这样做解决了问题: