自动装配不会创建存储库值

时间:2015-09-05 22:13:34

标签: java spring hibernate orm spring-data

我有以下课程

Sample.java

@Entity
@Table(name = "SAMPLE")

public class Sample extends Model {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "NAME")
        private String name;
    }
}

SampleRepository.java

@Repository
public interface SampleRepository extends CrudRepository<Sample, Long> {

    List<Sample> findByName(String name);
}

Application.java(主类)

public class Application {

@Autowired
SampleRepository repository;

public static void main(String args[]) {
    new Application().doThings();
}

public void doThings() {
    Sample sample = new Sample();
    sample.setName("arun");
    repository.save(sample);
}

}

我没有sprint-context.xml

当我尝试运行主类(Application.java)时,存储库对象始终为null。

我应该如何配置它以通过自动装配填充存储库对象中的值?

或者为什么存储库对象值总是为空?

2 个答案:

答案 0 :(得分:0)

让应用程序正常运行的最简单方法是使用Spring Boot。以下是命令行应用程序的示例:https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-simple

所以你的应用程序看起来像这样:

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    SampleRepository repository;


    @Override
    public void run(String... args) {
        this.repository.doThings();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Application.class);
        application.setApplicationContextClass(AnnotationConfigApplicationContext.class);
        SpringApplication.run(Application.class, args);
    }

    public void doThings() {
        Sample sample = new Sample();
        sample.setName("arun");
        repository.save(sample);
    }
}

答案 1 :(得分:-1)

因为您不在Java EE环境中(您有一个主方法),并且因为您没有在代码中初始化Spring。根据您要去的地方,查找相应的文档。