StackAsk is a community where developers ask questions, share answers and learn from each others real-world experience, so every solved problem helps the next person who runs into it.
@Qualifier
@Primary
public interface Ruler {}
public interface RulerImpl implements Ruler {}
@Retention(RetentionPolicy.RUNTIME) @interface Instant {} @Retention(RetentionPolicy.RUNTIME) @interface Inject {} class BeanManagement { public static void main(String[] args) throws Exception { EzyReflection reflections = new EzyReflectionProxy( "org.youngmonkeys.di" ); Set<Class<?>> classes = reflections.getAnnotatedClasses(Instant.class); Map<String, Object> beanByName = new HashMap<>(); Map<Class<?>, Object> beanByType = new HashMap<>(); for (Class<?> clazz : classes) { Object bean = clazz .getDeclaredConstructor() .newInstance(); beanByName.put(EzyClasses.getVariableName(clazz), bean); Class<?> parentClass = clazz; while (parentClass != null) { beanByType.put(parentClass, bean); parentClass = parentClass.getSuperclass(); } for (Class<?> inf : clazz.getInterfaces()) { beanByType.put(inf, bean); } injectDependenciesToBean(beanByName, beanByType, bean); } } public static void injectDependenciesToBean( Map<String, Object> beanByName, Map<Class<?>, Object> beanByType, Object bean ) throws Exception { Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Inject.class)) { // lấy phụ thuộc từ name trước, nếu không có thì lấy theo type Object dependency = beanByName.get( EzyClasses.getVariableName(field.getType()) ); if (dependency == null) { Class<?> parentClass = field.getType(); while (parentClass != null && dependency == null) { dependency = beanByType.get( parentClass ); parentClass = parentClass.getSuperclass(); } for (Class<?> inf : field.getType().getInterfaces()) { dependency = beanByType.get( inf ); if (dependency != null) { break; } } } field.setAccessible(true); field.set(bean, dependency); } } } }
"org.youngmonkeys.di"
2.2K Point(s)
1.2K Point(s)
313 Point(s)
178 Point(s)
138 Point(s)
Input your email to receive reset password link, or if you remember your password, you can click