@Autowired不起作用(未注入依赖项)

最后发布: 2015-07-24 22:21:41


问题

今天我春天有问题。 这是我的代码:


SpringConfig.java

package com.berrigan.addonsserver.springconfig;

import com.berrigan.addonsserver.EndPoint;
import org.glassfish.tyrus.server.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages={"com.berrigan.addonsserver","com.berrigan.addonsserver.modules"})
public class SpringConfig {
    @Bean
    public Server server(EndPoint end){
        return new Server("localhost",8025, "/margonem",null,end.getClass());
    }
}

EndPoint.java

package com.berrigan.addonsserver;

import com.berrigan.addonsserver.modules.ResponseGenerator;
import com.berrigan.addonsserver.util.JSONOutputTemplate;
import com.google.gson.Gson;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("endPoint")
@ServerEndpoint(value="/server")
public class EndPoint {

    @Autowired
    public ResponseGenerator rg;

    public EndPoint(){  System.out.println("Sucks");}
    public EndPoint(ResponseGenerator rg){ this.rg = rg; System.out.println("Rg is set");}

    @OnMessage
    public String onMessage(String message, Session s){
        Gson g = new Gson();
        if(rg == null) System.out.println("DI DOESN'T WORK");
        else{
        JSONOutputTemplate output = rg.generateResponse(null);//new JSONOutputTemplate();//
        g.toJson(output);
        }
        return message;
    }

    public void setResponseGenerator(ResponseGenerator rg){
        System.out.println("This works");
        this.rg = rg;
    }
}

ResponseGenerator.java

package com.berrigan.addonsserver.modules;

import com.berrigan.addonsserver.annotations.AuthorizationRequired;
import com.berrigan.addonsserver.util.JSONInputTemplate;
import com.berrigan.addonsserver.util.JSONOutputTemplate;
import org.springframework.stereotype.Component;

@Component
public class ResponseGeneratorImpl implements ResponseGenerator{

    @Override
    @AuthorizationRequired
    public JSONOutputTemplate generateResponse(JSONInputTemplate data) {
        return new JSONOutputTemplate();
    }
}

我的输出显示“ Sucks”和“ DI DOSN'T WORK”。 当我尝试从ApplicationConfig获取ResponseGenerator bean时,没有null。 我不知道怎么了 提前致谢。

java spring dependency-injection