Spring ioc dependency injection annotations
The following is the configuration file, which configures the scan path of spring. It does not work if this annotation is not configured.
package com.expect.oa.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.expect.oa.*") //@ComponentScan(basePackages={"com.expect.oa.DI.*","com.expect.oa.DI2.*"}) //Multiple packages can be written like this, which is equivalent to configuring automatic scanning in XML public class SpringConfig { }
Here is an interface:
package com.expect.oa.DI.interfaces; public interface InterA { void action1 (); }
The following declares a simple class that inherits the above interface:
package com.expect.oa.DI; import org.springframework.stereotype.Component; import com.expect.oa.DI.interfaces.InterA; @Component("interAImpl") //@Named("interAImpl") has the same effect public class CompA implements InterA{ @Override public void action1() { // TODO Auto-generated method stub System.out.println("spring DI"); } }
Here is the test code:
package com.expect.oa.test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.expect.oa.DI.interfaces.InterA; import com.expect.oa.config.SpringConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfig.class}) public class TestSpringDI { //Personal suggestion to name each component. @Resource(name="interAImpl") //@Autowired the same effect InterA aService; // here is the test dependency injection @Test public void testDI() { aService.action1 (); } }
![](/images/smiles/icon_biggrin.gif)