1.準備:aopパッケージをインポートする
2.beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--开启注解的支持-->
<context:annotation-config/>
<!--指定要扫描的包,这个包下的注解会生效-->
<context:component-scan base-package="com.tt"/>
</beans>
3.属性注入
3.1方法1
//@Component 组件等价于<bean id="user" class="com.tt.pojo.User"/>
@Component
//设置作用域
@Scope("singleton")
public class User {
public String name="甜甜";
public void setName(String name){
this.name = name;
}
}
3.2方法2
//@Component 组件等价于<bean id="user" class="com.tt.pojo.User"/>
@Component
public class User {
public String name;
//@Value相当于<property name="name" value="甜甜"/>
@Value("甜甜")
public void setName(String name){
this.name = name;
}
}
拡大する
@Componentにはいくつかの派生アノテーションがあります。Web開発では、mvcの3レイヤーアーキテクチャに従ってレイヤー化します。
これらの4つのアノテーション関数は、レイヤー化された表現のためだけに同じです。
- dao层【@Repository】
@Repository
public interface UserDao {
}
- サービス層【@Service】
@Service
public interface UserService {
}
- コントローラー层【@Controller】
@Controller
public class UserController {
}