Spring Boot - interfaces and implementations [duplicate]

血红的双手。 提交于 2019-12-13 04:54:20

问题


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

public interface ServiceInterface {
    static String serviceName = "service";
    public void displayMessage();
    public String getServiceName(); 
}

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 ?


回答1:


Never mind.. I just figured out that variables declared inside an interface are static and final.



来源:https://stackoverflow.com/questions/30111451/spring-boot-interfaces-and-implementations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!