且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用new创建对象时,Spring注入的bean为null,如何解决呢?

更新时间:2023-11-30 22:19:58

最终,我通过让AbstractRoom作为具有scope = prototype的bean解决了这个问题,并返回了实例

Eventually, I solve this problem with letting AbstractRoom as a bean with scope = prototype, and return the instance from roomservice bean.

@Configuration
@EnableAspectJAutoProxy
public class Application {      
    @Bean
    public CommandService commandService(){
        return new CommandService();
    }

    @Bean
    public RoomService roomService(){
        return new RoomService();
    }

    @Bean
    public GameService gameService(){
        return new GameService();
    }

    @Bean
    @Scope("prototype")
    public AbstractRoom room(AbstractRoom.Mode roomMode){
        RoomService roomService = roomService();
        return roomService.newRoom(roomMode);
    }

然后在RoomService.java中,注入 ApplicationContext ,然后从容器中获取房间。

And in RoomService.java , inject an ApplicationContext, and get Room from the container.

public class RoomService {

    @Autowired
    private ApplicationContext ctx;

    public AbstractRoom createRoom(String userID,int playerCount,Mode roomMode){
        AbstractRoom room = (AbstractRoom)ctx.getBean(AbstractRoom.class,roomMode);
    }
}