Поскольку вы работаете с AEM 6.4.x, я бы предложил использовать декларативные аннотации службы OSGi вместо аннотаций Felix SCR, как предлагали другие члены сообщества.
Чтобы использовать эти аннотации, я преобразовал ваш код в аннотации OSGi, заменив аннотации Felix SCR.
MyService.java
package org.redquark.aem.extensions.core.services;
public interface MyService {
/**
* This method returns the entered password into a hash equivalent with some
* properties passed by the user
*
* @param type
* @return {@link String}
*/
String getPassword(String type);
}
MyServiceImpl.java
package org.redquark.aem.extensions.core.services.impl;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
import org.redquark.aem.extensions.core.config.MyConfiguration;
import org.redquark.aem.extensions.core.services.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = MyService.class,
property = {
"label=My Service Implementation"
}
)
@Designate(ocd = MyConfiguration.class)
public class MyServiceImpl implements MyService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
// Two properties to be read
private String propertyOne;
private String propertyTwo;
@Activate
protected void activate(MyConfiguration config) {
// Reading properties from the configuration
propertyOne = config.getPropertyOne();
propertyTwo = config.getPropertyTwo();
}
@Override
public String getPassword(String type) {
// MD5 equivalent of password string
String passwordHash = null;
try {
type = type + propertyOne + propertyTwo;
log.info("Resulant password: " + type);
// Convert string to bytes - this is for the sample implementation (for show casing)
byte[] passwordByte = type.getBytes("UTF-8");
// Getting instance of MessageDigest
MessageDigest md = MessageDigest.getInstance("MD5");
// Convert bytes array to hash using MD5 algorithm
byte[] digest = md.digest(passwordByte);
passwordHash = new String(digest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return passwordHash;
}
}
Мы читаем наши пользовательские свойства в методе активации активации сервиса.
Аннотации свойств SCR дают вам большую свободу. Вы можете комментировать их в верхней части класса (используя аннотацию @ Properties в качестве контейнера с вложенными аннотациями @ Property ), вы можете аннотировать отдельные постоянные значения в качестве свойств. Вы можете сделать их видимыми в веб-консоли OSGI (технически вы создаете для них метатип) или можете пометить их как частные (метатип не создается).
С аннотациями OSGI все по-другому.
Свойства метатипа обрабатываются в выделенном классе конфигурации, отмеченном @ ObjectClassDefinition . Они не могут быть частными.
Свойства, которые считаются частными, прикрепляются к аннотации @ Component . Они больше не могут быть изменены.
Итак, для обработки этих свойств мы создадим отдельный интерфейс с аннотацией @ObjectClassDesfinition, а каждое свойство будет аннотировано @AttributeType.
MyConfiguration.java
package org.redquark.aem.extensions.core.config;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@ObjectClassDefinition(name = "My Configuration",
description = "This configuration will be used to read the value of properties.")
public @interface MyConfiguration {
@AttributeDefinition(name = "Property One", description = "Read property one", type = AttributeType.STRING)
public String getPropertyOne() default "Property One";
@AttributeDefinition(name = "Property Two", description = "Read property two", type = AttributeType.STRING)
public String getPropertyTwo() default "Property Two";
}
Теперь наконец-то приходит ваш сервлет -
MyServlet.java
package org.redquark.aem.extensions.core.servlets;
import java.io.IOException;
import javax.servlet.Servlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.redquark.aem.extensions.core.services.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = Servlet.class, property = { "sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.paths=" + "/bin/myservlet" })
public class MyServlet extends SlingAllMethodsServlet {
// Generated serialVersionUID
private static final long serialVersionUID = -8720724011172847122L;
private final Logger log = LoggerFactory.getLogger(this.getClass());
// Injecting reference of your service - No need to use BundleContext
@Reference
private MyService myService;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
// Calling the method implementation from your service
String password = myService.getPassword("Sample Type");
log.info("Writing password to the browser...");
response.getWriter().write(password);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Для демонстрации я позволил себе создать хеш-эквивалент пароля MD5, который также зависит от пользовательских свойств (propertyOne и propertyTwo). Вы можете написать свою реализацию JSON здесь.
Вы можете проверить другой пример с помощью службы планировщика здесь - https://aem.redquark.org/2018/10/day-13-schedulers-in-aem.html
Надеюсь, это поможет решить вашу проблему.
Удачного кодирования! Ура!