简体   繁体   English

Spring依赖注入与构造函数参数

[英]Spring dependency injection with constructor arguments

I have spring boot, hibernate application and android application for client side. 我有用于客户端的Spring Boot,Hibernate应用程序和Android应用程序。 Also I am using java.net.Socket api for socket connection. 我也使用java.net.Socket api进行套接字连接。 Before I was creating server socket like this new Server(12346); 在创建像这样的new Server(12346);服务器套接字之前, new Server(12346); and everything was good enough. 一切都很好。 But now I need access to database from socket class eg with @Autowired UsersDao field, but of course it is null because Socket class is not visible by Spring Framework. 但是现在我需要从套接字类(例如,使用@Autowired UsersDao字段)访问数据库,但是它当然为null因为Spring Framework无法看到Socket类。 So how do I make dependency injection on Socket class using port as constructor argument and make UserDao non-null? 那么,如何使用port作为构造函数参数对Socket类进行依赖注入,并使UserDao为非空?

You can access the Spring Application Context from static method and use this static method to load your repository bean in your Server class instead of autowiring it. 您可以从静态方法访问Spring Application Context ,并使用此静态方法将存储库bean加载到Server类中,而不是自动装配它。

You need to create the following classes (found here ): 您需要创建以下类(在此处找到):

ApplicationContextProvider ApplicationContextProvider

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;
    }
}

SpringConfiguration SpringConfiguration

@Configuration
public class SpringConfiguration {

    @Bean
    public static ApplicationContextProvider contextProvider() {
        return new ApplicationContextProvider();
    }

}

And then your non-Spring managed Server class: 然后是非Spring托管Server类:

public class Server {
    //your code

    public void doUsersDaoStuff() {
        UsersDao usersDao = (UsersDao) SpringConfiguration.contextProvider().getApplicationContext().getBean("UsersDao");
        // Do your own stuff with UsersDao here...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM