使用
1.1导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>
1.2 创建java类
public interface UserService {
public void doWork();
}
@Component
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public void doWork() {
System.out.println("UserServiceImpl.doWork");
userDao.doWork();
}
}
@Component
public class UserDao {
public void doWork(){
System.out.println("UserDao.doWork");
}
}
1.3 编写配置类
@Configuration
@ComponentScan(basePackages = {"com.binbin.dao","com.binbin.service"})
public class JavaConfig {
}
1.4 编写测试类
public class SpringTest {
@Test
void test(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);
UserService userService = (UserService) applicationContext.getBean("userServiceImpl");
userService.doWork();
}
}
UserServiceImpl.doWork
UserDao.doWork