【发布时间】:2015-06-17 11:34:05
【问题描述】:
我有一个非托管的 JPA 域类。它通过new 运算符实例化。
UserAccount account = new UserAccount();
userRepository.save(account)
在我的UserAccount 类中,我有一个beforeSave() 方法,它依赖于我的SecurityService 对密码进行哈希编码。
我的问题是“如何让 spring DI 将安全服务注入我的实体?”。似乎 AspectJ 和 LoadTimeWeaving 是我需要的。我已经尝试了一个配置数组,但我似乎无法让它们中的任何一个工作。尝试调用注入对象的方法时,我总是得到NullPointerException。
UserAccount.java(这是 JPA 实体)
@Entity
@Repository
@Configurable(autowire = Autowire.BY_TYPE)
public class UserAccount implements Serializable {
@Transient
@Autowired
SecurityService securityService;
private String passwordHash;
@Transient
private String password;
public UserAccount() {
super();
}
@PrePersist
public void beforeSave() {
if (password != null) {
// NullPointerException Here!!!
passwordHash = securityService.hashPassword(password);
}
}
}
试图指示spring使用AspectJ:
NitroApp.java(主类)
@SpringBootApplication
@EnableTransactionManagement
@EnableSpringConfigured
@PropertySources(value = {@PropertySource("classpath:application.properties")})
public class NitroApp extends SpringBootServletInitializer {
public static void main (String[] args) {
SpringApplication.run(NitroApp.class);
}
}
build.gradle(配置)
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:1.2.2.RELEASE"
classpath "org.springframework:springloaded:1.2.2.RELEASE"
classpath "org.springframework:spring-aspects:4.1.6.RELEASE"
}
}
apply plugin: 'java'
apply plugin: 'aspectj'
apply plugin: 'application'
apply plugin: 'idea'
apply plugin: 'spring-boot'
repositories {
jcenter()
mavenLocal()
mavenCentral()
}
mainClassName = 'com.noxgroup.nitro.NitroApp'
applicationName = "Nitro"
idea {
module {
inheritOutputDirs = false
outputDir = file("$buildDir/classes/main/")
}
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("net.sourceforge.nekohtml:nekohtml:1.9.15")
compile("commons-codec:commons-codec:1.9")
compile("org.postgresql:postgresql:9.4-1201-jdbc41")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
【问题讨论】:
-
您在运行应用程序时是否按照docs.spring.io/spring/docs/4.2.0.RC1/spring-framework-reference/… 中的说明正确启用加载时间编织?
-
@dunni 我在 4.1.6.RELEASE 的文档中。
标签: java spring spring-boot aspectj spring-aspects