Spring注釈配置解析

3732 ワード

非Web項目:Springコンテンツを直接読み込むには、Class PathXml Apple Controtextを借りる必要があります.
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
context.start();
 
 Webプロジェクト:Tomcatなどの容器はweb.xmlの内容をロードしますので、web.xmlには以下のように配置すればいいです.
<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
</context-param>
	
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
 Springの最も主要な構成はaplication.xmlであり、本文では注解構成のみを分析する.
 
  【appication.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/jdbc 
                        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context.xsd">
	
</beans>
  
 【自動ローディング】 
<context:component-scan base-package="com.test.action"/> <!--      -->
 
<context:component-scan base-package="com.test.action,com.test.service,com.test.impl"/> <!--      -->
 
 【注タイプ】
 @Component 管理コンポーネントの一般的な形式です.この注釈を追加すると、クラスをSpringに渡すという意味です.Spring 2.5には、@Repository(データアクセス層Daoなど)、@Service(サービス層Service)、@Controller(コントロール層、Web層)という追加の注釈が提供されています.ここでは、用途は異なる階層構造を区別し、将来のSpring対応の異なる階層の特殊機能と最適化に対応しています.
 
 @Controllerはコントロール層Bean、つまりアクションに対応します.ここではLoginnActionが自分(デフォルトでは「LoginnAction」またはvalue=「xxx」で新しい名前を付けて)をSpringに管理しています.その後はこの名前だけでホストのBeanを探し出して使用できます.
//@Controller(value="defineLoginAction")      
@Controller
@Scope("prototype")
public class LoginAction extends ActionSupport {
   ...
}
   
 @Serviceは業務層のBeanに対応しており、原理は上記の通りです.
@Service("loginService")
public class LoginService {
    ...
}
 
 @Repositoryはデータアクセス層Beanに対応しています.
@Repository(value="userDao")
public class UserDaoImpl implements UserDao{
    ......
}
 
 @ResourceはBeanを組み立てるために使用され、デフォルトでは名称によって組み立てられ、フィールドまたはsetter方法において、nameが指定されていない場合は、フィールドまたは属性名に従って組み立てられます.同じ名前のマッチが見つからない場合、タイプ別に組み立てることができます.
@Resource(name = "loginService")
private LoginService loginService;
    =(相当于)
LoginService loginService = new LoginService();
 
 @Autowired機能は@Resourceと同じで、デフォルトではタイプ別に組み立てられています.また、依存対象が存在しなければなりません.もしnullであれば、required属性をfalseとして設定します.例えば、@Autowired(required=false)は、名称組立を使用したいなら@Qualfier注解と組み合わせて使用できます.
@Autowired() @Qualifier("userDao")     
private UserDao userDao;