I am trying to access my database and return some of the results. I have watched a bunch of tutorials but each one seems to be off. Right now the @Autowired is giving an error of 'No Beans of UserRepository type found If anyone could help me it would be greatly appreciated. Here is what I have so far.
Controller
package com.rdopler.ecommerceTest.controller;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path="/user")
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping
public String check() {
return "Welcome";
}
@GetMapping(path="/getusernames")
public List<String>getAllUserNames() {
return userRepository.getAllUserNames();
}
}
Repo
package com.rdopler.ecommerceTest.repository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
@Autowired
JdbcTemplate jdbcTemplate;
public List<String> getAllUserNames() {
List<String> usernameList = new ArrayList<>();
usernameList.addAll(jdbcTemplate.queryForList("select * from employees ", String.class);
return usernameList;
}
}
application.properties
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/storeDB?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=*****
Main:
package com.rdopler.ecommerceTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EcommerceTestApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceTestApplication.class, args);
}
}
请尝试在主类中添加@EnableJpaRepositories(“ packagename”)。
In your main app try adding this annotation below @SpringBootApplication
@ComponentScan(basePackages = "com.rdopler.ecommerceTest")
It will help you to scan all your components. Also if you have any service(s) in your application, make sure you annotate that/those with @Service annotation.
将@Component添加到类UserRepository
在UserRepository中添加@Transactional,也在主类中添加@ComponentScan。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.