我正在将spring批注@CreatedBy
用于createdBy,将@LastModifiedBy
用于updateBy-
@CreatedBy
@Field(value = "createdBy")
private String createdBy;
@LastModifiedBy
@Field(value = "updatedBy")
private String updatedBy;
我还在主应用程序中使用过@EnableMongoAuditing
这个注释。
并创建了一个实现AuditorAware
的类,如下所示-
@Component
public class UserAudtiting implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
String uname = SecurityContextHolder.getContext().getAuthentication().getName();
return Optional.of(uname);
}
}
因此,当我使用某种发布方法来保存数据时,我得到“ createdBy”:null 作为响应。
我应该怎么做?请帮忙!
答案 0 :(得分:0)
为了启用审核,我们需要添加到Spring配置中。可以使用XML或JAVA Config
Spring XML Configuraton
<mongo:auditing />
<mongo:mongo id="mongo" />
<bean class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="blog-tests" />
</bean>
Spring Java配置
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.abc")
@EnableMongoRepositories(basePackages = "com.abc.xyz.repository")
@EnableMongoAuditing
public class MongoApplicationConfiguration {
@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
MongoCredential mongoCredential = MongoCredential.createCredential("user", "test", "samp".toCharArray());
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
return new SimpleMongoDbFactory(mongoClient, "test");
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
要使用@CreatedBy和@LastModifiedBy,您需要告诉Spring谁是当前用户。
首先将与用户相关的字段添加到您的审核类中:
@CreatedBy
private String createdBy;
@LastModifiedBy
private String lastModifiedBy;
然后创建您的AuditorAware实现,该实现将获取当前用户(可能是从会话或Spring Security上下文中获取的-取决于您的应用程序):
public class UserAudtiting implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
// get your user name here
String uname = SecurityContextHolder.getContext().getAuthentication().getName();
return Optional.of(uname);
}
}
最后一件事是通过对Mongo配置进行少量修改来告知Spring Data MongoDB有关该审计师的类:
<mongo:auditing auditor-aware-ref="auditor" />
<bean id="auditor" class="app.demo.UserAudtiting "/>
此处有更多详细信息:https://www.javacodegeeks.com/2013/05/auditing-entities-in-spring-data-mongodb.html
答案 1 :(得分:0)