fag*_*ani 4 java spring ioc-container autowired java-ee
我有一个带Component
注释的接口和一些实现它的类如下:
@Component
public interface A {
}
public class B implements A {
}
public class C implements A {
}
Run Code Online (Sandbox Code Playgroud)
另外,我有一个类Autowired
变量,如下所示:
public class Collector {
@Autowired
private Collection<A> objects;
public Collection<A> getObjects() {
return objects;
}
}
Run Code Online (Sandbox Code Playgroud)
我的上下文文件包含以下定义:
<context:component-scan base-package="org.iust.ce.me"></context:component-scan>
<bean id="objectCollector" class="org.iust.ce.me.Collector" autowire="byType"/>
<bean id="b" class="org.iust.ce.me.B"></bean>
<bean id="c" class="org.iust.ce.me.C"></bean>
Run Code Online (Sandbox Code Playgroud)
在主要课程中,我有一些代码如下:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
B b = (B) context.getBean("b");
C c = (C) context.getBean("c");
Collector objectCollector = (Collector) context.getBean("objectCollector");
for (A object : objectCollector.getObjects()) {
System.out.println(object);
}
Run Code Online (Sandbox Code Playgroud)
输出:
org.iust.ce.me.B@1142196
org.iust.ce.me.C@a9255c
Run Code Online (Sandbox Code Playgroud)
这些代码运行良好,但由于某些原因,我不愿意使用xml上下文文件.除此之外,我更喜欢用new
运算符创建对象而不是使用getBean()
方法.然而,由于AutoWiring
编程中的确是个好主意,我不想失去它.
现在我有两个问题!!
如何AutoWire
在A
不使用xml上下文文件的情况下实现接口的类?
有可能吗?
当我改变了scope
一个bean从singlton
到
prototype
如下:
<bean id="b" class="org.iust.ce.me.B" scope="prototype"></bean>
和实例化了好豆,只就创建过程中实例化的豆context
,是injected
为AutoWired
变量.为什么?
任何帮助将不胜感激.
不确定您使用的是Spring版本.但目前您可以使用@Configuration
替换.xml.看看@Configuration
以下是文档中的代码
@Configuration
public class ServiceConfig {
private @Autowired RepositoryConfig repositoryConfig;
public @Bean TransferService transferService() {
return new TransferServiceImpl(repositoryConfig.accountRepository());
}
}
@Configuration
public interface RepositoryConfig {
@Bean AccountRepository accountRepository();
}
@Configuration
public class DefaultRepositoryConfig implements RepositoryConfig {
public @Bean AccountRepository accountRepository() {
return new JdbcAccountRepository(...);
}
}
@Configuration
@Import({ServiceConfig.class, DefaultRepositoryConfig.class}) // import the concrete config!
public class SystemTestConfig {
public @Bean DataSource dataSource() { /* return DataSource */ }
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class);
TransferService transferService = ctx.getBean(TransferService.class);
transferService.transfer(100.00, "A123", "C456");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15503 次 |
最近记录: |