1 /*
2 * Copyright 2020 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.bremersee.spring.core;
18
19 import java.lang.reflect.Method;
20 import org.aopalliance.intercept.MethodInterceptor;
21 import org.springframework.aop.framework.ProxyFactory;
22 import org.springframework.core.Ordered;
23
24 /**
25 * The ordered proxy.
26 *
27 * @author Christian Bremer
28 */
29 public abstract class OrderedProxy {
30
31 /**
32 * Instantiates a new ordered proxy.
33 */
34 private OrderedProxy() {
35 }
36
37 /**
38 * Create a proxy of the target object that implements {@link Ordered}.
39 *
40 * @param <T> the type of the proxy
41 * @param target the target
42 * @param orderedValue the ordered value
43 * @return the type of the proxy; if the target implements one or more interfaces, it must be one
44 * of these interfaces, otherwise it must be {@link Ordered}
45 */
46 public static <T> T create(Object target, int orderedValue) {
47 if (target instanceof Ordered && ((Ordered) target).getOrder() == orderedValue) {
48 //noinspection unchecked
49 return (T) target;
50 }
51 ProxyFactory proxyFactory = new ProxyFactory(target);
52 if (!(target instanceof Ordered)) {
53 proxyFactory.addInterface(Ordered.class);
54 }
55 proxyFactory.addAdvice((MethodInterceptor) methodInvocation -> {
56 Method method = methodInvocation.getMethod();
57 if (method.getName().equals("getOrder") && method.getParameterCount() == 0) {
58 return orderedValue;
59 } else {
60 return methodInvocation.proceed();
61 }
62 });
63 //noinspection unchecked
64 return (T) proxyFactory.getProxy();
65 }
66
67 }