简体   繁体   中英

How to autowire a bean into a 2 different controllers (Spring)

I am learning spring and i have a problem that i do not know how to solve.

@Service
@Transactional
public class SchoolService {

   @Autowired
   private CourseDao courseDao;
   @Autowired
   private EducationDao educationDao;
   @Autowired
   private StudentDao studentDao;
   @Autowired
   private TeacherDao teacherDao;
   @Autowired
   private StatisticsDao statisticsDao;


............
}

This code is injecting my DAOS into this service class but then i need to inject the class above into two controllers. One way i have tried was with this code but that did not work.

    @Autowired
    SchoolService sm;

How would i inject it into my controller class. I have tried making the controller class a @Component but nothing seems to work.

ClassPathXmlApplicationContext container = new ClassPathXmlApplicationContext("application.xml");

SchoolService sm = container.getBean(SchoolService.class);

This way works but i do not want to create a new applicationcontext for each time i want to get that bean.

Yes i am using xml at the moment, please don't shoot me :D Thanks.

尝试在application.xml文件中创建控制器 bean 而不是注释控制器。

Since its obviously an educational question, I'll try to provide a very detailed answer as much as I can:

Once basic thing about spring that all the auto-wiring magic happens only with beans that are managed by spring.

So:

  • Your controllers must be managed by spring
  • Your service must be managed by spring
  • Your DAOs must be managed by spring

Otherwise, autowiring won't work, I can't stress it more.

Now, Think about the Application Context as about the one global registry of all the beans. By default the beans are singletons (singleton scope in terms of spring) which means that there is only one object (instance) of that bean "retained" in the Application Context.

The act of autowiring means basically that the bean (managed by spring) - controller in your case has dependencies that spring can inject by looking in that global registry, getting the matching bean and setting to the data field on which the @Autowired annotation is called.

So, if you have two controllers (again, both managed by spring), you can:

@Controller
public class ControllerA {
   @Autowired
   private SchoolService sm;
}


@Controller
public class ControllerB {
   @Autowired
   private SchoolService sm;
}

In this case, the same instance of school service will be injected into two different controllers, so you should good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM