java-依赖注入到Spring非托管bean中

我有一个非托管的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);  
        }
    }
}

试图表明跳动使用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'
}

解决方法:

您可以在用于实例化UserAccount的类中注入Spring applicationContext.

@Autowired
private ApplicationContext applicationContext;

然后,通过以下方式创建UserAccount bean:

UserAccount userAccount = applicationContext.getBean(UserAccount.class);

这样,您可以在UserAccount类中注入所需的依赖项.

上一篇:春天-类型化/泛型方面值得努力吗?


下一篇:java-如何使用AspectJ访问私有字段?