[英]How can i see the output of an autowired method inside a config class
@Configuration
@ComponentScan(basePackages = "com.test")
public class Config {
@Autowired
public int fun(SampleClass obj) {
return obj.num;
}
@Bean
public SampleClass get() {
return new SampleClass();
}
}
In this code I can call the Bean method from my main class like this,在这段代码中,我可以像这样从我的主要 class 调用 Bean 方法,
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
SampleClass obj = ctx.getBean(SampleClass.class);
But how can I call the Autowired method.但是我怎么能调用 Autowired 方法。 Or if i cannot then where can i see the output to the same.或者如果我不能,那么我在哪里可以看到 output 相同。
And also this is my SampleClass.java这也是我的 SampleClass.java
public class SampleClass {
int num;
SampleClass(){
System.out.println("inside constructor of sample class");
num = 4;
}
}
as-is
as-is
问题Config
class is also a bean, so calling its method is quite straightforward: Config
class 也是一个 bean,所以调用它的方法非常简单:
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
Config config = ctx.getBean(Config.class);
SampleClass sampleClass = ctx.getBean(SampleClass.class);
System.out.println(config.fun(sampleClass));
@Autowired
on method works可能对@Autowired
on 方法的工作方式有误解I think you might misunderstood how this works.我想你可能误解了它是如何工作的。 When you put @Autowired
on a regular method, spring only treats this method as init method , ie spring calls it once during context initialisation and that is it.当您将@Autowired
放在常规方法上时, spring 仅将此方法视为 init 方法,即 spring 在上下文初始化期间调用它一次,仅此而已。 It doesn't change behaviour of this method if you are going to call it directly.如果您要直接调用它,它不会改变此方法的行为。
As a hands-on exercise, add System.out.println("Init");
作为动手练习,添加System.out.println("Init");
in fun()
method and create context without any method calls ( ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
You will see that Init
will be printed.在fun()
方法中并在没有任何方法调用的情况下创建上下文( ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
您将看到Init
将被打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.