Для более общего решения, которое работает независимо от количества измерений, используйте copy.deepcopy()
:
import copy
b = copy.deepcopy(a)
Поскольку вы используете Spring Boot, я предполагаю, что вы предпочтете, когда это возможно, полагаться на автоматическую настройку Spring. Чтобы добавить дополнительную настраиваемую конфигурацию, например, ваши перехватчики, просто укажите конфигурацию или компонент WebMvcConfigurerAdapter
.
Вот пример класса конфигурации:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
HandlerInterceptor yourInjectedInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(...)
...
registry.addInterceptor(getYourInterceptor());
registry.addInterceptor(yourInjectedInterceptor);
// next two should be avoid -- tightly coupled and not very testable
registry.addInterceptor(new YourInterceptor());
registry.addInterceptor(new HandlerInterceptor() {
...
});
}
}
ПРИМЕЧАНИЕ не комментируйте это с @EnableWebMvc, если вы хотите сохранить автоматическую конфигурацию Spring Boots для mvc .
Вы также можете подумать о добавлении зависимостей SpringSandwich, которые позволяют вам напрямую комментировать ваши контроллеры, к которым применяются перехватчики, точно так же, как вы комментируете свои маршруты URL (раскрытие: я автор).
Чтобы добавить перехватчик в приложение загрузки весны, выполните следующие
public class MyCustomInterceptor implements HandlerInterceptor{
//unimplemented methods comes here. Define the following method so that it
//will handle the request before it is passed to the controller.
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response){
//your custom logic here.
return true;
}
}
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
}
}
WebMvcConfigurerAdapter
будет устаревать с помощью Spring 5. Из его Javadoc :
@deprecated с 5.0 {@link WebMvcConfigurer} имеет методы по умолчанию (стало возможным с помощью базовой линии Java 8) и может быть реализована непосредственно без использования этого адаптера
blockquote>Как указано выше, вам следует реализовать
WebMvcConfigurer
и переопределить методaddInterceptors
.@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyCustomInterceptor()); } }
У меня была та же проблема, что и для WebMvcConfigurerAdapter. Когда я искал примеры, я почти не нашел реализованного кода. Вот фрагмент рабочего кода.
создайте класс, который расширяет HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String x = request.getMethod();
logger.info(x + "intercepted");
return true;
}
}
, а затем реализует интерфейс WebMvcConfigurer
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
EmployeeInterceptor employeeInterceptor ;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
}
}