spring--(14)利用註解創建bean與bean之間的關係

xml配置文件app

<!-- 掃描com.test.annotation包下全部的類 -->
	<context:component-scan base-package="com.test.annotation">
	</context:component-scan>

main文件ide

public static void main(String[] args) throws SQLException {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserController userController = (UserController) ctx.getBean("userController");
		userController.excute();
		
		
	}

controller文件ui

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	public void excute() {
		System.out.println("UserController excute...");
		userService.add();
	}
}

service文件code

@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;
	
	public void add() {
		System.out.println("UserService add...");
		userRepository.save();
	}
}

接口文件component

public interface UserRepository {
	
	public void save();

}

接口實現層文件xml

@Repository
public class UserRepositoryImpl implements UserRepository {

	@Override
	public void save() {
		System.out.println("UserRepository Save...");
	}

}

利用@Autowired註解實現bean與bean之間的聯繫,上述main方法輸出接口

UserController excute...
UserService add...
UserRepository Save...

2、IOC沒有裝配的bean
testObject文件get

//@Component
public class TestObject {
	
	public void name() {
		System.out.println("TestObject ...");
	}
}

這個bean沒有加上@Component註解,所以ioc容器不會加載它,可是又須要用到它,則需進行以下處理it

@Repository
public class UserRepositoryImpl implements UserRepository {

	//設置required=false
	@Autowired(required=false)
	private TestObject testObject;
	
	@Override
	public void save() {
		System.out.println("UserRepository Save...");
		System.out.println(testObject);
	}
}

3、指定惟一bean
如今UserRepository接口有兩個實現類,上面有一個,如今添加一個io

@Repository
public class UserJdbcRepositoryImpl implements UserRepository{

	@Override
	public void save() {
		System.out.println("UserJdbcRepositoryImpl save...");
	}
}

以下代碼就不知道該調用哪一個實現類的save方法

@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;
	
	public void add() {
		System.out.println("UserService add...");
		//這裏不知道調用哪一個實現類的save方法
		userRepository.save();
	}
}

爲了指定調用哪一個save方法,則須要指定實現接口的哪一個類,修改以下

@Service
public class UserService {
	
	@Autowired
	@Qualifier("userJdbcRepositoryImpl")
	private UserRepository userRepository;
	
	public void add() {
		System.out.println("UserService add...");
		//這裏指定了實現類UserJdbcRepositoryImpl
		userRepository.save();
	}
}
相關文章
相關標籤/搜索