Spring Boot-接口和实现 [英] Spring Boot - interfaces and implementations
问题描述
Java/Spring新手在这里.我有一个关于通过SpringBoot自动接线的问题.
Java/Spring newbie here. I've a question about auto wiring through SpringBoot.
我有一个接口,一个实现,一个主类和一个配置类,就像这样:
I have an interface , an implementation , a main class and a configuration class like so :
ServiceInterface.java
ServiceInterface.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");
}
}
主要班级:
@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
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
为什么ServiceImpl1实现中的变量'serviceName'无法通过Spring通过自动装配创建的对象访问?
Why is the variable 'serviceName' inside ServiceImpl1 implementation not accessible through the object created by Spring through autowiring ?
推荐答案
Never mind.. I just figured out that variables declared inside an interface are static and final.
这篇关于Spring Boot-接口和实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!