[英]Spring not wire beans
我开始学习 spring 并想尝试一个例子。 我写了 3 个类 bellow bat 似乎我遗漏了一些东西,因为 String 没有做我打算做的事情。
package testPackage;
import org.springframework.beans.factory.annotation.*;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes=Config.class)
public class TestDrive {
@Autowired
private InterfaceClass obj;
public static void main(String[] args) {
TestDrive testDrive = new TestDrive();
System.out.println(testDrive.obj);
}
}
package testPackage;
import org.springframework.context.annotation.*;
public class TestClass implements InterfaceClass {
public String test = "test string";
@Bean
public TestClass getTestClass() {
TestClass testClass = new TestClass();
return testClass;
}
}
package testPackage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class Config {
}
当我从 main 运行此代码时,我会打印“null”。 为什么 Spring 不连接“InterfaceClass obj”?
谢谢!
1)在标记为@Configuration的类中声明你的Spring Beans
2) 在main函数中,使用 ApplicationContext 来获取 TestDrive 对象。 切勿将 Spring bean 对象与从 new 运算符创建的对象混合使用
试驾课程
public class TestDrive {
@Autowired
private InterfaceClass obj;
@Autowired
private ApplicationContext appContext;
public static void main(String[] args) {
//you will have to use this method, to get bean of TestDrive
// You should not use new operator, not advisable to mix new operator with spring beans
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
TestDrive drive = context.getBean(TestDrive.class);
System.out.println(drive.getString());
}
public String getString(){
String str = obj.getTestString();
return str;
}
}
测试类
public class TestClass implements InterfaceClass{
public String test = "test string";
public String getTestString(){
return test;
}
}
接口类
public interface InterfaceClass {
public String getTestString();
}
配置
@Configuration
public class Config {
@Bean
public InterfaceClass getTestClass() {
TestClass testClass = new TestClass();
return testClass;
}
@Bean
public TestDrive getTestDrive(){
return new TestDrive();
}
}
将@Configuration
注释放在测试类的顶部:-
package testPackage;
import org.springframework.context.annotation.*;
@Configuration
public class TestClass implements InterfaceClass {
public String test = "test string";
@Bean
public TestClass getTestClass() {
TestClass testClass = new TestClass();
return testClass;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.