我试图修复错误,但我无法找到如何解决这部分:
这是错误。程序运行了一下,然后抛出空指针
Properties value: DEVELOPEMENT
App is running...
Exception in thread "main" java.lang.NullPointerException
at hu.citec.hazi.hazi.service.Service.print(Service.java:12)
at hu.citec.hazi.hazi.Main.run(Main.java:26)
at hu.citec.hazi.hazi.Main.main(Main.java:20)
我的代码:回购类:
package hu.citec.hazi.hazi.repo;
import java.time.LocalDateTime;
@org.springframework.stereotype.Repository
public class RepoImpl implements Repository {
public String getPropertyMsg() {
StringBuilder sb = new StringBuilder("Hello");
sb.append("\n")
.append("\t").append("HOME: ").append(System.getProperty("user.dir")).append("\n")
.append("\t").append("USER: ").append(System.getProperty("user")).append("\n")
.append("\t").append("TIME: ").append(LocalDateTime.now()).append("\n");
return sb.toString();
}
public String runTest(String msg) {
System.err.println(msg);
return msg;
}
}
仓库界面:
package hu.citec.hazi.hazi.repo;
public interface Repository {
String getPropertyMsg();
String runTest(String msg);
}
服务等级:
package hu.citec.hazi.hazi.service;
import hu.citec.hazi.hazi.repo.Repository;
@org.springframework.stereotype.Service
public class Service {
private Repository repo;
public String print() {
return repo.getPropertyMsg();
}
public String test(String msg) {
return repo.runTest(msg);
}
}
MainConfig 类:
package hu.citec.hazi.hazi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import hu.citec.hazi.hazi.entity.User;
@ComponentScan("hu.citec.hazi.hazi")
@PropertySource({ "classpath:application.properties", "classpath:application-${spring.active.profiles}.properties" })
public class MainConfig {
@Bean
public User defaultUser(@Value("${project.profile.name}") String name) {
System.out.println("Properties value: "+ name );
return new User(name);
}
}
主类:
package hu.citec.hazi.hazi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import hu.citec.hazi.hazi.config.MainConfig;
import hu.citec.hazi.hazi.service.Service;
@Component
public class Main {
@Autowired
private Service service;
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
Main main = ctx.getBean(Main.class);
main.run();
}
public void run() {
System.out.println("App is running...");
System.out.println("ÜDV! \n\t" + service.print() + "\n " +service.test("Sikeres teszt"));
}
}
也许我犯了一些错误。对于那个很抱歉。
我还必须写更多的细节来使这个 qquestion 通过。