archivo de propiedades se ve así:
url1=path_to_binary1 url2=path_to_binary2De acuerdo con esto , probé el siguiente enfoque:
@Component @EnableConfigurationProperties public class ApplicationProperties { private Map<String, String> pathMapper; //get and set }y en otro componente conecté automáticamente ApplicationProperties:
@Autowired private ApplicationProperties properties; //inside some method: properties.getPathMapper().get(appName); produce NullPointerException .
¿Cómo corregirlo?
Tengo el consejo correcto según el usuario 7757360:
@Component @EnableConfigurationProperties @ConfigurationProperties(prefix="app") public class ApplicationProperties {y archivo de propiedades:
app.url1=path_to_binary1 app.url2=path_to_binary2todavía no funciona
@Component @EnableConfigurationProperties @ConfigurationProperties(prefix="app") public class ApplicationProperties { private Map<String, String> app; y dentro application.properties :
app.url1=path_to_binary1 app.url2=path_to_binary2todavía no funciona
sería útil si pudiera dar un ejemplo más específico para el archivo de propiedad. Debe tener el mismo prefijo en url1 y url2 y luego puede usar
@ConfigurationProperties(prefix="my")
como en
my.pathMapper.url1=path_to_binary1 my.pathMapper.url2=path_to_binary2
@Component @EnableConfigurationProperties @ConfigurationProperties(prefix="my") public class ApplicationProperties { private Map<String, String> pathMapper; //get and set for pathMapper are important }NullPointerException es probablemente de ApplicationProperties vacío.
Todas las propiedades personalizadas deben anotarse como @ConfigurationProperties(prefix="custom") . Después de eso, en su clase principal (clase con método principal) debe agregar @EnableConfigurationProperties(CustomProperties.class) . Para autocompletar puedes usar:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> Si usa @ConfigurationProperties sin prefijo, solo usa el nombre del campo. Nombre del campo en sus propiedades. En su caso path-mapper , a continuación, key y value específicos. Ejemplo:
path-mapper.key=valueRecuerde que después de realizar cambios en sus propias propiedades, debe volver a cargar la aplicación. Ejemplo:
Hay dos cosas que necesita para alimentar el mapa desde el archivo de propiedades. Primero, debe tener una clase que tenga la configuración y los campos de destino para almacenar datos del archivo de propiedades.
@Configuration @PropertySource("classpath:myprops.properties") @ConfigurationProperties("props") @Component public class Properties{ private Map<String,String> map = new HashMap<String,String>(); // getter setter }En segundo lugar, defina el archivo de propiedades llamado myprops.properties con todas las propiedades como accesorios.
props.map.port = 443 props.map.active = true props.map.user = aUser