XML配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean class="com.fossians.maven_courses.Say_Impl" id="id_Say_Impl" />
</beans>
Say_I
public interface Say_I
{
public void Say_I_m1();
}
Say_Impl
public class Say_Impl implements Say_I
{
public void Say_I_m1()
{
System.out.println("inside : public void Say_I_m1() \n");
}
}
控制器:
public class Controller_Test implements SpringApplicationContextInterface
{
@Autowired
private Say_Impl say_Impl;
//Below line not assigning, need to reassign into method
private Say_I say_I = (Say_I) say_Impl;
// private Say_I say_I = (Say_I) applicationContext.getBean("id_Say_Impl");
@RequestMapping(value = "/test10")
public String Test1()
{
say_I = say_Impl;
System.out.println("Say_Impl_auto : "+say_Impl);
System.out.println("Say_I : "+say_I);
say_I.Say_I_m1();
return " request value = test10 ";
}
}
public interface SpringApplicationContextInterface
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanConfig.xml");
}
@SpringBootApplication
@ImportResource("classpath:beanConfig.xml")
public class Courses extends SpringBootServletInitializer
{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(Courses.class);
}
}
上面的代码是spring boot应用程序的一部分。
“Controller_Test”类中的这行代码:
private Say_I say_I = (Say_I) say_Impl;
未将Say_Impl对象“say_Impl”引用分配给其父对象say_I。但是,如果我再次将它分配给Test1()方法,那么它正在工作。
但下面的代码行将say_Impl引用分配给say_I对象。
private Say_I say_I = (Say_I) applicationContext.getBean("id_Say_Impl");
现在我的问题是,当我通过自动装配获取say_impl对象时为什么我需要将其重新分配给方法?有没有办法让它在没有重新分配的情况下工作?
当我通过应用程序上下文获取bean时,我不需要重新分配,为什么?
答案 0 :(得分:1)
非常难看的代码,带有spring boot WTF的旧版xml?
试试这个
@Autowired
private Say_I say_I;
或更好:
@SpringBootApplication
public class Courses {
public static void main(String[] args) {
SpringApplication.run(Courses.class, args);
}
@RestController
public class Controller_Test {
@Autowired
private Say_I say_I;
@RequestMapping(value = "/test10")
public String Test1() {
System.out.println("Say_I : " + say_I);
say_I.Say_I_m1();
return " request value = test10 ";
}
}
@Component
public class Say_I {
void Say_I_m1() {
System.out.println("inside : public void Say_I_m1() \n");
}
}
}