我遇到了一个奇怪的问题,其中注入(inject)了 @Autowire
的 Component
在一个类中可用,但在另一个类中不可用。
我在Account
和Agreement
类的属性network
中使用@Autowired
,但它是 Autowiring 的仅在Agreement
类中,但不在Account
类中。 @ComponentScan
运行 3 个所需的包。
这是开始类(class):
package com.ser.pm.tests;
@SpringBootApplication
@ComponentScan("com.ser.pm.agreement, com.ser.pm.network, com.ser.pm.address")
public class zt_Agreement {
public static void main(String[] args) throws SignatureException, InterruptedException {
ApplicationContext ctx = SpringApplication.run(zt_Agreement.class, args);
Agreement oagreement = ctx.getBean(Agreement.class);
oagreement.SubmitAgreement();
}
}
这是组件
Network
,它也必须注入(inject)到Account
->network
中
package com.ser.pm.network;
@Component
public class Network implements INetwork {
public X2network xsnetwork;
public Network() { xsnetwork = networkFactory.createnetwork(); }
public boolean isBound() { return (xsnetwork != null); }
public BigInteger getNumber(byte[] addr) { return xsnetwork.getNumber(addr); }
}
在此类中,字段network
未 Autowiring :
package com.ser.pm.address;
@Component
public class Account implements IFSAccount {
@Autowired
Network network;
public Account(String ir_Address, String ir_Name) {}
public Account() {}
public BigInteger getNumber() {
return network.getNumber(Hex.decode(this.getAddress()));
}
}
在此类中,字段network
已正确自动连接
package com.ser.pm.agreement;
@Component
public class Agreement {
protected Account oFSEthAddress;
private Trans oTx;
private AgreementABI oABIs;
@Autowired
Network network;
@Autowired
private ApplicationContext ctx;
public Agreement() {
oFSEthAddress = new Account();
oagreementAccountOil = new FSEthagreementAccount();
}
public Trans JoinAgreement(String iPrivateKey) throws FScx {
FSNetGas oFSEthNetGas = new FSNetGas();
oFSEthAddress.setEtherum(oNetwork.onetwork);
SCTrans oFSTx = new FSTrans();
oFSTx.createCallTrans(_oTxParams);
oFSTx.submit(oNetwork.onetwork);
return oFSTx.getTrans();
}
}
类Account
和Agreement
位于不同的包中,但它们都是用@ComponentScan
扫描的,因此我不明白为什么我在 Account
类中的 Autowiring 有问题?
最佳答案
您没有使用 spring 来获取 Account 实例 - 所以 spring 没有机会 Autowiring 它。这一行:
oFSEthAddress = new Account();
关于java - spring - 组件在一个类中 Autowiring ,但不在另一个类中 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35293726/