1 註解注入
註解:就是一個類,使用@註解名稱
開發中:使用註解 取代 xml配置文件
1.1 @Component
@Component 取代 <bean class="">
@Component("id") 取代 <bean id="" class="">
1.2 web開發,提供3個@Component
註解衍生註解(功能一樣)取代<bean class="">
2 測試
2.1 xml 配置
package com. tzb. service;
import com. tzb. model. User;
public interface IUserService {
public void add ( ) ;
public void add ( User user) ;
}
package com. tzb. service;
import com. tzb. model. User;
public class UserServiceImpl implements IUserService {
private String name;
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
@Override
public void add ( ) {
System. out. println ( "添加用戶:" + name) ;
}
@Override
public void add ( User user) {
System. out. println ( "添加用戶:" + user) ;
}
}
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id = "userService" class="com.tzb.service.UserServiceImpl"></ bean>
</ beans>
@Test
public void test ( ) {
ApplicationContext context = new ClassPathXmlApplicationContext ( "beans10.xml" ) ;
IUserService service = ( IUserService) context. getBean ( "userService" ) ;
User user = new User ( ) ;
user. setUsername ( "Mike" ) ;
service. add ( user) ;
}
2.2 使用註解
package com. tzb. service;
import com. tzb. model. User;
import org. springframework. stereotype. Component;
@Component
public class UserServiceImpl implements IUserService {
private String name;
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
@Override
public void add ( ) {
System. out. println ( "添加用戶:" + name) ;
}
@Override
public void add ( User user) {
System. out. println ( "添加用戶:" + user) ;
}
}
<?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: annotation-config>
</ context: annotation-config>
< context: component-scan base-package = " com.tzb" > </ context: component-scan>
</ beans>
@Test
public void test ( ) {
ApplicationContext context = new ClassPathXmlApplicationContext ( "beans10.xml" ) ;
IUserService service = context. getBean ( UserServiceImpl. class ) ;
User user = new User ( ) ;
user. setUsername ( "Mike" ) ;
service. add ( user) ;
}