我正在尝试创建一个可通过 OSGi 控制台进行配置的 Java 类。我听说你可以通过 SCR 注释来做到这一点,但不完全确定如何做。我已经掌握了大部分内容,但不确定要获取和发布什么以及如何在 JSP 中引用它。这是我到目前为止所拥有的:
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import javax.servlet.ServletException;
import java.io.IOException;
@SlingServlet(
paths={"/somepath/"}
)
@Properties({
@Property(name="email.add", value="Email Info",propertyPrivate=false),
@Property(name="user.info",value="User Info", propertyPrivate=false)
})
public class WelcomeMessage extends SlingAllMethodsServlet
{
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
//Do something here
}
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
//Do something here
}
}
最佳答案
为了能够处理此类注释,您需要设置 Maven SCR 插件(来自 Apache Felix)。该插件将处理注释并在生成的 JAR 文件中创建元数据。
@SlingServlet 注释是 Apache Sling 特定的,并且需要某些 Apache Sling 包才能注册 servlet。 @SlingServlet 注释也由 Maven SCR 插件处理。
这是有关如何在 Maven 中配置 SCR 插件的示例。
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.9.0</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
此外,为了能够创建 OSGi bundle (带有 OSGi 元数据的 Jar),您需要设置 Maven Bundle 插件。
您可以在此处找到有关 Maven SCR 插件的简短文档:http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin.html 。
Maven Bundle 插件文档位于:http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html .
但是,理解这一点的最佳方法是查看此处 Sling bundle 中的示例:https://github.com/apache/sling/tree/trunk/bundles 。
关于java - 来自 OSGI 的可配置 Java Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711567/