问题
I run into a strange problem where a Component
injected with @Autowire
is available in one class, but not in another one.
I use @Autowired
in the attribute network
of the classes Account
and Agreement
, but it is autowired only in the class Agreement
but not in Account
. The @ComponentScan
runs over the 3 needed packages.
Here is the start 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();
}
}
Here is the Component
Network
which has to be injected in the Account
->network
too
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); }
}
In this class the field network
is not autowired:
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()));
}
}
In this class the field network
is autowired correctly
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();
}
}
The classes Account
and Agreement
are in different packages but both of them are scanned with @ComponentScan
, therefore I don't understand why I have problems with the autowiring in the class Account
?
回答1:
You are not using spring to obtain Account instance - so spring did not get a chance to autowire it.this line :
oFSEthAddress = new Account();
来源:https://stackoverflow.com/questions/35293726/spring-component-autowired-in-one-class-but-not-in-another