初入spring時的幾種常用標籤
1,先將一個小專案簡單的分成四層
controller,service,dao,entity
2,@Controller
@Controller
public class TestController {
@Autowired
@Qualifier("userServiceImp")//方便選擇合適例項類,畢竟一個服務層的介面可能會有多個例項類
private UserService userService;
public TestController() {
}
public void printName(User u) {
System.out.println("controller printName:"+u.getName());
userService.printName(u);
}
}
3,@Service
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userdao;
public UserServiceImp() {
}
@Override
public void printName(User u) {
System.out.println("service printName:"+u.getName());
userdao.printName(u);
}
}
4,@Repository
@Repository
public class UserDaoImp implements UserDao {
public UserDaoImp() {
}
@Override
public void printName(User u) {
System.out.println("dao printName:"+u.getName());
}
}
除了第一個控制器的標籤,其他標籤都是用來自動裝載的
5,配置檔案內容
<?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">
<!-- 使用context名稱空間,通過Spring掃描指定包下所有Bean的實現類,進行註解解析 -->
<context:component-scan base-package="com"/>
</beans>
6,測試類
ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");//手動獲取配置檔案物件
TestController testcon = (TestController)appCon.getBean("testController"); //從物件中獲取bean
testcon.printName( new User( "Super Man", 20 )) ;
下面再放上要匯入的jar包
commons-logging-1.2.jar
spring-beans-5.0.2.RELEASE.jar
spring-context-5.0.2.RELEASE.jar
spring-core-5.0.2.RELEASE.jar
spring-expression-5.0.2.RELEASE.jar
jar包的檔案我也會上傳
寫這篇是為了說明這幾種常用標籤使用的位置