我试图从函数中获取值但未能获取。我尝试添加componentscan但是我失败了

时间:2017-11-20 12:17:27

标签: java spring spring-boot spring-boot-maven-plugin

我试图从函数中获取值但是失败了。我尝试添加componentscan但是我失败了。

主要方法

package org.vik.springstarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@SpringBootApplication
public class MyMain {
     public static void main(String[] args) {
        SpringApplication.run(MyMain.class, args);
    }
}

用户类

package org.vik.data;

public class UserData {
    private Integer Id;
    private String name;
    private String address;

    public UserData(Integer Id,String name,String address){
        this.Id = Id;
        this.name = name;
        this.address = address;
    }
    public Integer getId() {
        return Id;
    }
    public void setId(Integer id) {
        Id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

用户服务

package org.vik.data;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
@Component
public class UserService {

    private List<UserData> userlist = Arrays.asList(
        new UserData(1,"Vik","sdfdsf"),
        new UserData(1,"Abani","sdfdsf"),
        new UserData(1,"Abrar","sdfdsf")
    );

    public List<UserData> getAlluser(){
        return userlist;
    }
 }

用户控制器

package org.vik.data;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userservice;
    @RequestMapping("/hello")
    public List<UserData> Hello(){
        return userservice.getAlluser();
    }
    @RequestMapping("/vik")
    public String hi(){
        return "hi";
    }
}
  

***************************申请失败

           

说明

     

org.vik.springstarter.controller.HelloController中的字段用户服务   需要一个类型为#org.vik.data.UserService&#39;的bean。那不可能   找到。

     

动作:

     

考虑定义类型&#39; org.vik.data.UserService&#39;的bean。在你的   配置。

1 个答案:

答案 0 :(得分:0)

您的Application.class采用不同的包结构:

  

package org.vik.springstarter;

只需将Application.class移动到与服务相同的结构:

  

org.vik