2016-12-25 6 views
-1

ребята. У меня есть для вас один вопрос. Я внедряю приложение для входа в систему, которое имеет контроллер XML-RPC для разрешения запросов и обслуживания (реализует службу SpringDetails службы Spring) для входа в систему. Данные для входа пользователя хранятся во встроенной базе данных mongodb с доступом к DAO. Так что, когда я вхожу в систему, служба с помощью dao попадает в базу данных для пользователей. Hovewer, в момент вызова службы DAO не инициализируется (имеет значение NULL). Что я делаю не так? Мой класс контроллера:Spring не инициализирует автообновленный компонент DAO при обслуживании под контроллером XML-RPC

@Controller 
public class XmlRpcController { 
private XmlRpcServletServer server; 

@Autowired 
private UserService userService; 

@PostConstruct 
public void init() throws XmlRpcException { 
    try { 
     System.out.println("Starting the server on port 8090"); 
     XmlRpcServerConfigImpl config= new XmlRpcServerConfigImpl(); 

     server=new XmlRpcServletServer(); 
     server.setConfig(config); 

     PropertyHandlerMapping xmlRpcHandlerMapping=new PropertyHandlerMapping(); 
     xmlRpcHandlerMapping.load(Thread.currentThread().getContextClassLoader(),"xmlrpc.properties"); 
     server.setHandlerMapping(xmlRpcHandlerMapping); 
     System.out.println("The server started successfully."); 

    } catch (Exception e) { 
     System.err.println("Server Error: " + e); 
     throw new XmlRpcException(e.getMessage()); 
    } 
} 

@RequestMapping("xmlrpc") 
public void serve(HttpServletRequest request, HttpServletResponse response) throws XmlRpcException { 
    try { 
     server.execute(request,response); 
    } catch (Exception e) { 
     throw new XmlRpcException(e.getMessage(), e); 
    } 
} 
} 

W xmlrpc.properties службы определяется для реализации запросов:

service=org.vkalashnykov.service.UserService 

Услуги:

@Service 
public class UserService implements UserDetailsService{ 
    @Autowired 
    private UserDAO userDAO; 

@Override 
    public UserDetails loadUserByUsername(@NotNull String username) throws UsernameNotFoundException { 
     return userDAO.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("user "+username+ " was not found")); // Here the userDAO is null 
    } 

    public String login(@NotNull String username, @NotNull String password){ 
     User user=(User)loadUserByUsername(username); 
     if (user!=null && user.getPassword().equals(new BCryptPasswordEncoder().encode(password))) 
      return Statuses.SUCCESS.name(); 
     else 
      return Statuses.ERROR.name(); 
    } 
} 

DAO:

@Component 
public class UserDAO{ 

@Autowired 
MongoTemplate mongoTemplate; 

public Optional<User> findByUsername(@NotNull String username){ 
    return Optional.ofNullable(mongoTemplate.findOne(
      query(
        where(UserField.USER_NAME.getField()).is(username)), 
        User.class)); 
} 

public void save(User user){ 
    mongoTemplate.save(user); 
} 

} 

Spring Секу Конфигурация rity:

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter{ 
@Autowired 
private UserService userService; 

@Bean 
public BCryptPasswordEncoder getBCryptPasswordEncoder(){ 
    return new BCryptPasswordEncoder(); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
      .antMatchers("/xmlrpc").permitAll() 
      .and() 
      .csrf().disable(); 
} 

@Autowired 
@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userService).passwordEncoder(getBCryptPasswordEncoder()); 
} 
} 

На стороне клиента есть приложение, которое отправляет имя пользователя и пароль для сервера для входа в систему:

@FXML 
private TextField login; 

@FXML 
private TextField password; 

private String configuration="xmlrpc"; 

private final String serverUrl="http://localhost:8090/xmlrpc"; 

private final XmlRpcClient xmlRpcClient=new XmlRpcClient(); 

public Controller() throws Exception { 
    final XmlRpcClientConfigImpl config=new XmlRpcClientConfigImpl(); 
    try { 
     System.out.println("Trying connect to server "+serverUrl); 
     config.setServerURL(new URL(serverUrl)); 
    } catch (MalformedURLException e) { 
     System.err.println("Server "+serverUrl+" not found."); 
     e.printStackTrace(); 
     errorLabel.setText("Server not found."); 
     throw new Exception("Server not found."); 
    } 
    xmlRpcClient.setConfig(config); 
    System.out.println("Connected to server: "+serverUrl); 
} 
+0

Итак, вы ожидаете, что экземпляр класса не управляется весной, чтобы его впрыскивали и контролировали весной ... Ваша инфраструктура RPC контролирует экземпляр, а не Spring, поэтому ничего не будет автообновлено. –

+0

Есть ли способ, которым я могу управлять весенними бобами с RPC? –

ответ

0

Я изменил конфигурацию контроллера для структуры Apache XML-RPC в следующем виде:

@Controller 
public class XmlRpcController { 
    private XmlRpcServletServer server; 
    @Autowired 
    UserService userService; 

    @PostConstruct 
    public void init() throws XmlRpcException { 
    try { 
     SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 
     System.out.println("Starting the server on port 8090"); 
     XmlRpcServerConfigImpl config= new XmlRpcServerConfigImpl(); 

     server=new XmlRpcServletServer(); 
     server.setConfig(config); 

     PropertyHandlerMapping xmlRpcHandlerMapping=new PropertyHandlerMapping(); 
     xmlRpcHandlerMapping.setRequestProcessorFactoryFactory(pClass->pRequest->userService); 
     xmlRpcHandlerMapping.addHandler(UserService.class.getSimpleName(),UserService.class); 
     XmlRpcSystemImpl.addSystemHandler(xmlRpcHandlerMapping); 
     server.setHandlerMapping(xmlRpcHandlerMapping); 
     System.out.println("The server started successfully."); 

    } catch (Exception e) { 
     System.err.println("Server Error: " + e); 
     throw new XmlRpcException(e.getMessage()); 
    } 
    } 
} 

Похоже на работу, теперь DAO полностью инициализирован. Спасибо.