Nếu bạn sử dụng lò xo bối cảnh trong dự án của bạn: Dưới đây là một ví dụ làm việc để liệt kê tất cả các loại với chú thích mong muốn:
/**
* Lists all types in the given package (recursive) which are annotated by the given annotation.
* <p>
* All types which match the criteria are returned, no further checks (interface, abstract, embedded, etc.
* are performed.
* <p>
*
* @param aAnnotation
* the desired annotation type
* @param aRoot
* the package name where to start the search.
* @return a list of found types
*/
private Collection<? extends Class<?>> findCandidatesByAnnotation(Class<? extends Annotation> aAnnotation,
String aRoot)
{
List<Class<?>> result = new ArrayList<Class<?>>();
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false)
{
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition)
{
return true;
}
};
scanner.addIncludeFilter(new AnnotationTypeFilter(aAnnotation));
Set<BeanDefinition> canditates = scanner.findCandidateComponents(aRoot);
for (BeanDefinition beanDefinition : canditates)
{
try
{
String classname = beanDefinition.getBeanClassName();
Class<?> clazz = Class.forName(classname);
result.add(clazz);
}
catch (ClassNotFoundException t)
{
myLog.error("Springs type scanner returns a class name whose class cannot be evaluated!!!", t);
}
}
return result;
}
này mã đã được thử nghiệm với spring-context-4.1.1.RELEASE dưới java 8.
nếu bạn cung cấp thêm một chút thông tin về lý do bạn muốn thực hiện - như trường hợp bạn đang gặp phải, có thể thực hiện theo cách khác và chưa đạt được kết quả tương tự. – Chii