使用基于弹簧网的项目时,弹簧配置文件无法解决

时间:2017-02-28 07:56:47

标签: spring spring-mvc spring-boot

给出的application.properties中的

:spring.profiles.active = DEV 并在dev配置文件中:提到所有mongo连接属性

并添加了配置java文件,如

@Configuration

@PropertySource("classpath:userIdentity_Dev.properties")

@Profile("DEV")
public class UserIdentityConfigDev
{

}

运行应用程序时,弹出探测器无法解析

收到

以下的堆栈跟踪

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userIdentityService': Unsatisfied dependency expressed through field 'userIdentityBusiness'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userIdentityBusiness': Unsatisfied dependency expressed through field 'userIdentityRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userIdentityRepositoryImpl': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'mongodb.userIdentity.host' in string value "${mongodb.userIdentity.host}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)

说$ {mongodb.userIdentity.host}属性未解析

为项目创建war和jar文件时,弹簧配置文件未解析

1 个答案:

答案 0 :(得分:0)

这是主要课程:

`@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})

@PropertySource( “类路径:application.properties”)

public class ApplicationStart扩展了SpringBootServletInitializer {

public static void main(String [] args)

{

    SpringApplication.run(ApplicationStart.class,args);

}

}`

下面是属性文件:

## MongoDB Connection Properties-----------------

MongoDB数据库

mongodb.userIdentity.database = UserIdentity_CS

isConnectionStringUsed为true然后应用程序根据connectionString创建连接,否则它将使用MongoDB单服务器属性。

mongodb.userIdentity.isConnectionStringUsed = false

connectionString with authentication

mongodb.connectionString = mongodb:// sa:测试%40123 @ SPT-CPU-0259:27017,SPT-CPU-0173:27017 / admin?replicaSet = surveillens

connectionString without authentication

mongodb.userIdentity.connectionString = mongodb:// localhost:27017 /?replicaSet = surveillens

MongoDB单服务器属性。

mongodb.userIdentity.host = localhost

mongodb.userIdentity.port = 27017

身份验证属性

mongodb.userIdentity.isAuthenticationEnable = false

mongodb.userIdentity.userName = sa

mongodb.userIdentity.password = Test @ 123

mongodb.userIdentity.authDB = admin

用户标识的集合名称

mongodb.userIdentity.collectionName = CreditScore

其他属性-----------------------

userIdentity.ValidKeySet = email; phonenumber; _id

userIdentity.logsFolder = ./IdentityLogs /

userIdentity.insertBatchSize = 100

及以下是文件.java文件,其中使用了所有这些属性 ` @组态 公共抽象类MongoDbRepository {

private Class<T> clazz;
private static MongoClient mongoClient = null;
private static MongoDatabase mongoDatabase = null;
private static ObjectMapper mapper = null;

@Value("${mongodb.userIdentity.host}")
private  String mongoHost;

@Value("${mongodb.userIdentity.port}")
private int mongoPortNumber;

@Value("${mongodb.userIdentity.database}")
private String mongoDatabaseName;

@Value("${mongodb.userIdentity.userName}")
private String mongoUserName;

@Value("${mongodb.userIdentity.authDB}")
private String mongoAuthDB;

@Value("${mongodb.userIdentity.password}")
private String mongoPassword;

@Value("${mongodb.userIdentity.isAuthenticationEnable}")
private boolean mongoIsAuthEnable;

@Value("${mongodb.userIdentity.isConnectionStringUsed}")
private boolean mongoIsConnectionStringUsed;

@Value("${mongodb.userIdentity.connectionString}")
private String mongoConnectionString;

public final void setClazz(Class<T> clazzToSet)
{
    this.clazz = clazzToSet;
}

/**
 * Instantiates a new mongo base repository.
 * @throws Exception
 */
public MongoDbRepository()
{
    //Trigger MongoDB Connection initialization

    if(mongoClient == null)
    {
        prepareMongoConnection();
    }
    else
    {
        // Trigger any method to check MongoDB client is connected
        mongoClient.getAddress();
    }

    // Trigger ObjectMapper initialization
    if(mapper == null)
        prepareObjectMapper();
}

/**
 * Instantiates a new mongoDB connection.
 * @throws Exception
 */
private void prepareMongoConnection()
{
    if (mongoConnectionString != null && !mongoConnectionString.isEmpty())
    {
        boolean isConnectionStringUsed = mongoIsConnectionStringUsed;

        if(isConnectionStringUsed)
        {
            MongoClientURI clientUri = new MongoClientURI(mongoConnectionString);
            mongoClient = new MongoClient(clientUri);
        }
        else
        {
            if(mongoIsAuthEnable)
            {
                MongoCredential credential = MongoCredential.createCredential(mongoUserName, mongoAuthDB, mongoPassword.toCharArray());
                mongoClient = new MongoClient( new ServerAddress(mongoHost, mongoPortNumber), Arrays.asList(credential));
            }
            else
                mongoClient = new MongoClient(mongoHost, mongoPortNumber);
        }

        // Trigger any method to check MongoDB client is connected
        mongoClient.getAddress();
        // Get Database from mongoClient.
        mongoDatabase = mongoClient.getDatabase(mongoDatabaseName);
    }
}

/**
 * Get an objectMapper.
 */
private void prepareObjectMapper()
{
    mapper = CommonFunctions.getObjectMapper();
}

/**
 * Get the MongoDB collection object from MongoDB.
 *
 * @param collectionName is Name of a MongoDB collection
 * @return Collection object
 * @throws Exception
 */
private MongoCollection<Document> getCollection(String collectionName) throws Exception
{
    if(mongoClient == null)
        prepareMongoConnection();
    return mongoDatabase.getCollection(collectionName);
}

/*   ------- Find functions -------   */

/**
 * Find one documents from mongoDB collection.
 *
 * @param collectionName the collection name
 * @param query the query document - set to empty document means no query filtering.
 *
 * @return entityObj the entity Object
 * @throws Exception the exception
 */
public T findOne(String collectionName, Object query) throws Exception
{
    if(clazz == null)
        throw new NullPointerException("ST224 - Generic class is null - set the generic class before perform MongoDB operation");

    MongoCollection<Document> collection = getCollection(collectionName);
    Document mongoDoc = collection.find(convertToBsonDocument(query)).first();

    String jsonStr = mapper.writeValueAsString(mongoDoc);
    T entityObj =  mapper.readValue(jsonStr, clazz);

    return entityObj;
}

}`