弹簧启动中的原始类型依赖注入

时间:2018-01-11 14:00:49

标签: java spring spring-mvc spring-config

您能否在春季启动时向我提供原始类型依赖注入的示例。我曾尝试过一次,但TestConfiguration是我的自定义bean定义类,它不会被Spring启动应用程序检测到或无法识别。 这是我的代码,

//引擎类

package com.test2.projectTest;

import org.springframework.stereotype.Component;

@Component
public class Engine {

private String msg;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

//测试配置

package com.test2.projectTest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {

@Bean("engine")
public Engine engine(){
    Engine engine = new Engine();
    engine.setMsg("Message is injected");
    return engine;
}
}

// spring main application

package com.test2.projectTest;

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class ProjectTestApplication {

public static void main(String[] args) {
    SpringApplication.run(ProjectTestApplication.class, args);
}
}

// JUnit Test

package com.test2.projectTest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import 
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProjectTestApplicationTests {

@Test
public void contextLoads() {

    ApplicationContext apc = new 
AnnotationConfigApplicationContext(TestConfiguration.class);
    Engine e = (Engine) apc.getBean("engine");
    e.getMsg();
}
}

// Output - org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'engine' available

请建议上述问题的任何解决方案

1 个答案:

答案 0 :(得分:0)

在主类中添加@componentscan注释并提供引擎类包,它应该可以工作