java Spring Boot - 接口和实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30111451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot - interfaces and implementations
提问by anset
Java/Spring newbie here. I've a question about auto wiring through SpringBoot.
Java/Spring 新手在这里。我有一个关于通过 SpringBoot 自动布线的问题。
I have an interface , an implementation , a main class and a configuration class like so :
我有一个接口、一个实现、一个主类和一个配置类,如下所示:
ServiceInterface.java
服务接口.java
public interface ServiceInterface {
static String serviceName = "service";
public void displayMessage();
public String getServiceName();
}
ServiceImpl1.java
ServiceImpl1.java
public class ServiceImpl1 implements ServiceInterface{
static String serviceName = "default service value ";
public String getServiceName() {
return serviceName;
}
@Override
public void displayMessage()
{
System.out.println("This is implementation 1");
}
}
The main class :
主要类:
@SpringBootApplication
public class App implements CommandLineRunner{
@Autowired
private ServiceInterface serviceInterface;
public static void main(String args[])
{
SpringApplication.run(App.class, args);
}
@Override
public void run(String... args) {
serviceInterface.displayMessage();
System.out.println(serviceInterface.getServiceName());
System.out.println(serviceInterface.serviceName );
}
}
AppConfig.java
应用程序配置文件
@Configuration
public class AppConfig {
@Bean
ServiceInterface serviceInterface()
{
return new ServiceImpl1();
}
}
When I run the code , I get this as the output
当我运行代码时,我得到这个作为输出
This is implementation 1
service 1
default service value
Why is the variable 'serviceName' inside ServiceImpl1 implementation not accessible through the object created by Spring through autowiring ?
为什么无法通过 Spring 通过自动装配创建的对象访问 ServiceImpl1 实现中的变量“serviceName”?
采纳答案by anset
Never mind.. I just figured out that variables declared inside an interface are static and final.
没关系.. 我刚刚发现在接口内声明的变量是静态的和最终的。