Vytvoríme si vlastnú anotáciu pre triedy. Potom niekoľko tried roztrúsime po packageoch a necháme Springové záležitosti, aby našli tie správne triedy a potom jednej z nich aj zavoláme.
DOWNLOAD CODE HERE. Tu si stiahni cely projekt. Malicke to je. Par tried. Vyskusaj.
Toľko toho bolo na začiatku - malá nočná hudba o troch súboroch. Zožeň Maven. Otvor cmd v adresári kde je kód a píš: "mvn install eclipse:eclipse" A ideš!
zaciname odtial - prazdny projekt
pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.perhac.blog</groupId>
<artifactId>component-scanning</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>ComponentScanning</name>
<description>This will use Spring internals to scan for classes annotated with
a custom annotation. Spring core/beans/context version 2.5+ required to run
this example. Java 7 used, but not required.</description>
<properties>
<spring.version>4.1.2.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- logging: logback over slf4j, because it rocks!
-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
logback.xml
<configuration>
<appender
name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by
default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
FindComponents.java (first-stab)
package com.perhac.blog.component_scanning;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FindComponents {
private static final Logger LOG = LoggerFactory.getLogger(FindComponents.class);
public static void main(String[] args) throws IOException {
LOG.info("Ready to roll!");
}
}
Tak si vytvorme niekolko tried, co poanotujeme novou anotaciou:
MyComponent.java (annotation)
package com.perhac.blog.component_scanning;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyComponent {
String value();
}
A potom dopiseme tento kod do FindComponents triedy. Toto spusti hladanie anotovanych tried vsade v urcenom package-i a package-och v nom ulozenych.
FindComponents.java (imporved - finds annotated classes)
package com.perhac.blog.component_scanning;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
public class FindComponents {
private static final Logger LOG = LoggerFactory.getLogger(FindComponents.class);
private static final String BASE_PACKAGE = FindComponents.class.getPackage().getName();
public static void main(String[] args) throws Exception {
LOG.info("Ready to roll!");
Set<Class<?>> myComponentClasses = findAnnotatedClasses(BASE_PACKAGE);
for (Class<?> myClass : myComponentClasses) {
MyComponent annotation = myClass.getAnnotation(MyComponent.class);
LOG.info("Found name: \"{}\" of type:
{}",
annotation.value(), myClass.getName());
}
}
private static Set<Class<?>>
findAnnotatedClasses(String basePackage) throws ClassNotFoundException {
ClassPathScanningCandidateComponentProvider
componentProvider = new ClassPathScanningCandidateComponentProvider(false);
componentProvider.addIncludeFilter(new
AnnotationTypeFilter(MyComponent.class));
Set<BeanDefinition> candidateComponents =
componentProvider.findCandidateComponents(basePackage);
Set<Class<?>> classesFound = new HashSet<>();
for (BeanDefinition beanDefinition : candidateComponents) {
classesFound.add(Class.forName(beanDefinition.getBeanClassName()));
}
return classesFound;
}
}
Takto jednu z tried vyberieme a spustime jej main() methodu pomocou reflection:
FindComponents.java (final)
package com.perhac.blog.component_scanning;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
public class FindComponents {
private static final Logger LOG = LoggerFactory.getLogger(FindComponents.class);
private static final String BASE_PACKAGE = FindComponents.class.getPackage().getName();
public static void main(String[] args) throws Exception {
LOG.info("Ready to roll!");
Set<Class<?>> myComponentClasses = findAnnotatedClasses(BASE_PACKAGE);
Map<String, Class<?>> classMap = new HashMap<>();
for (Class<?> myClass : myComponentClasses) {
MyComponent annotation = myClass.getAnnotation(MyComponent.class);
LOG.info("Found name: \"{}\" of type:
{}",
annotation.value(), myClass.getName());
classMap.put(annotation.value(), myClass);
}
Class<?> classToRun = classMap.get("hidden");
Method mainMethod = classToRun.getMethod("main", String[].class);
mainMethod.invoke(null, new Object[] { new String[] { "Peter
Perhac", "Brighton, UK", "November 25, 2014" } });
}
private static Set<Class<?>>
findAnnotatedClasses(String basePackage) throws ClassNotFoundException {
ClassPathScanningCandidateComponentProvider
componentProvider = new ClassPathScanningCandidateComponentProvider(false);
componentProvider.addIncludeFilter(new
AnnotationTypeFilter(MyComponent.class));
Set<BeanDefinition> candidateComponents =
componentProvider.findCandidateComponents(basePackage);
Set<Class<?>> classesFound = new HashSet<>();
for (BeanDefinition beanDefinition : candidateComponents) {
classesFound.add(Class.forName(beanDefinition.getBeanClassName()));
}
return classesFound;
}
}
Takto to vyzera u mna v projekte, vy ste si mozno vykuzlili ine triedy. Je jedno ake, kym ste ich anotovali @MyComponent.
finalna verzia - vsetky subory projektu
Zvolenu triedu HiddenClass.java uvediem pre kompletnost:
HiddenClass.java
package com.perhac.blog.component_scanning.dummy.nested;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.perhac.blog.component_scanning.MyComponent;
@MyComponent("hidden")
public class HiddenClass {
private static final Logger LOG = LoggerFactory.getLogger(HiddenClass.class);
public static void main(String[] args) {
LOG.info("Hello from: " + HiddenClass.class.getName());
LOG.debug(Arrays.toString(args));
}
}
A vysledok prenadherny, ako sa dalo cakat:
21:50:09.211 [main] INFO c.p.b.c.FindComponents - Ready to roll!
21:50:09.371 [main] INFO c.p.b.c.FindComponents - Found name:
"two" of type: com.perhac.blog.component_scanning.another_dummy.ClassTwo
21:50:09.371 [main] INFO c.p.b.c.FindComponents - Found name:
"one" of type: com.perhac.blog.component_scanning.dummy.ClassOne
21:50:09.371 [main] INFO c.p.b.c.FindComponents - Found name:
"hidden" of type: com.perhac.blog.component_scanning.dummy.nested.HiddenClass
21:50:09.371 [main] INFO c.p.b.c.dummy.nested.HiddenClass - Hello
from: com.perhac.blog.component_scanning.dummy.nested.HiddenClass
21:50:09.371 [main] DEBUG c.p.b.c.dummy.nested.HiddenClass -
[Peter Perhac, Brighton, UK, November 25, 2014]
DOWNLOAD CODE HERE. Tu si stiahni cely projekt. Malicke to je. Par tried. Vyskusaj. |