spring5.x版本 java配置和annotation配置說明

人生如遊戲---發表於2018-03-08

java配置

@Configuration //這個註解的意思是相當於把此類當作一個xml檔案
public class AppConfig {
	
	@Bean(name="userService")  //這個註解相當於xml檔案裡的<bean> 
	public UserService userService() {
		UserService service = new UserService();
		service.setUserDAO(userDAOIml());
		return service;
	}
	
	@Bean
	public UserDAOIml userDAOIml() {
		return new UserDAOIml();
	}
	
}
public class UserServiceTest {

	@Test
	public void testAdd() {
		ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
//		UserService service = (UserService)context.getBean(UserService.class);
		UserService service = (UserService)context.getBean("userService");
		User user = new User();
		user.setName("xxx");
		user.setPassword("123456");
		service.add(user);
	}

}

這樣就不需要XML檔案了。直接用類名或者Bean名都可以獲取。

Annotation配置

首先XML配置

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 	開啟annotation配置 -->
    <context:annotation-config/>
<!--    掃描以com開頭的包裡邊的bean -->
    <context:component-scan base-package="com"/>
    

</beans>

接著用@Repository配置這兩個實現同一個介面的DAO。

@Repository
public class UserDAOIml implements UserDAO {
	@Override
	public void save(User user) {
		// TODO Auto-generated method stub
		System.out.println("UserDAOIml: -----save a user");
	}
}


@Repository
public class UserDAOIml2 implements UserDAO {
	@Override
	public void save(User user) {
		// TODO Auto-generated method stub
		System.out.println("UserDAOIml2: -----save a user");
	}
}

接下來配置呼叫的類

@Service
public class UserService {
	@Autowired
	@Qualifier("userDAOIml2")   //如果沒有這句就會報錯,Spring不知道該注入哪個實現類
	private UserDAO userDAO;

	public UserService() {
		// TODO Auto-generated constructor stub
		System.out.println("初始化");
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public void add(User user) {
		userDAO.save(user);
	}
}

試過不加@Service也能執行成功,暫時不知道啥情況

呼叫方法

	@Test
	public void testAdd() {
		ApplicationContext context = new ClassPathXmlApplicationContext("benasAnnotation.xml");	
		UserService service = (UserService)context.getBean(UserService.class);
		User user = new User();
		user.setName("xxx");
		user.setPassword("123456");
		service.add(user);
	}

}

Spring提供四種配置bean的註解。目前測試暫時效果都一樣的

@Component      @Controller    @Service        @Repository   回頭用的時候再補充吧

相關文章