IOC @Autowired与new创建的对象
1.添加配置的类
@Component public class ThriftComponent { @Value("${thrift.host}") public String host; @Value("${thrift.port}") public int port; @Value("${thrift.timeout}") public int timeout; }
2.添加客户端类
public class ThriftClient { private final static Logger log = LoggerFactory.getLogger(ThriftClient.class); // @Autowired // private ThriftComponent tComponent; private TBinaryProtocol protocol; private TSocket transport; private String host; private int port; private int timeout; public ThriftClient(String h, int p, int t) { // tComponent.host // tComponent.port // tComponent.timeout//不能直接在这里使用 host = h; port= p; timeout = t; } }
3.使用方法
@Autowired private ThriftComponent tComponent;
ThriftClient tClient = new ThriftClient(tComponent.host,tComponent.port,tComponent.timeout);
4.@Autowired注入Spring Bean,则当前类必须也是Spring Bean才能调用它,不能用new xxx()来获得对象,这种方式获得的对象无法调用@Autowired注入的Bean。