编程语言
首页 > 编程语言> > java-依赖注入到Spring非托管bean中

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类中注入所需的依赖项.

标签:spring-boot,aspectj,spring-aspects,spring,java
来源: https://codeday.me/bug/20191028/1950569.html