简单的Spring应用程序中的依赖注入不起作用(将Service注入Controller变量)

时间:2015-01-17 21:49:40

标签: java spring dependencies autowired code-injection

我有一个非常简单的项目。

它有主要类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

控制器:

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class Controller {

    @Autowired
    MyService myService;

    @RequestMapping("/application")
    public String getApp(ModelMap model) {
        return "application";
    }

    @RequestMapping("/application/home")
    public String do(@RequestParam(value="input", required=false) String input, ModelMap model) {
        if (!StringUtils.isEmpty(input)) {
            model.addAttribute(INPUT_ATT, input);
            model.addAttribute(OUTPUT_ATT, myService.do(input));
        }
        return "home";
    }

}

服务(接口,实现):

package com.example;

public interface MyService {

    String do(String input);
}

package com.example;

import org.springframework.stereotype.Service;

@Service
public class MyServiceImpl implements MyService {

    @Override
    public String do(String input) {
        return "result";
    }

}

不幸的是,MyServiceImpl的一个实例没有被注入到控制器类中的myService变量中。

我该怎么做才能解决这个问题?

关于,

3 个答案:

答案 0 :(得分:1)

您的代码未编译,因为'做'是一个关键字。但除此之外,你的代码应该没问题。我也尝试使用SpringBoot进行轻微修改

应用

@SpringBootApplication
public class Application {

    /**
     * Run the Web Application using built-in Tomcat server.
     * This is used for testing only
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

控制器

@RestController
public class HelloworldController {

    @Autowired
    private IHelloworldHelper helper;

    @RequestMapping("/hello")
    public Helloworld hello(String name) {
        return new Helloworld(1, helper.doAction(name));
    }
}

辅助

@Service
public class HelloworldHelper implements IHelloworldHelper {

    @Override
    public String doAction(String name) {
        return String.format("Hi %s!", name);
    }
}

public interface IHelloworldHelper {

    public String doAction(String name);
}

模型

public class Helloworld {

    private long id;
    private String content;

    public Helloworld(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

答案 1 :(得分:0)

您的Application类应如下所示。

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.example" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }
//other configuration

}

和启动应用程序的WebAppInitializer类应与此类似

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(MvcConfig.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");    
    }   
 }

答案 2 :(得分:0)

将@ImportResource参数添加为“spring application context xml path”

@ComponentScan
@EnableAutoConfiguration
@ImportResource("applicationContext.xml")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}