spring 常见的注解

spring中的注解都必须在配置文件中进行如下的配置:

<context:component-scan base-package="com.shanjin.oxm.service.impl,com.shanjin.oxm,com.shanjin.interceptorh,com.shanjin.oxm.service" />

1、@Component

@Component
是所有受Spring 管理组件的通用形式,@Component注解可以放在类的头上,@Component不推荐使用。

2、@Controller

@Controller对应表现层的Bean,也就是Action,例如:

3、@ Service

@Service对应的是业务层Bean,例如:

@Service("elasticsearchService")注解是告诉Spring,当Spring要创建elasticsearchServiceImpl的的实例时,bean的名字必须叫做"elasticsearchService",这样当Action需要使用elasticsearchServiceImpl的的实例时,就可以由Spring创建好的"elasticsearchService",然后注入给Action:在Action只需要声明一个名字叫“elasticsearchService”的变量来接收由Spring注入的"elasticsearchServicee"即可

4、@ Repository

@Repository对应数据访问层Bean

/**
 * @author 何婷婷
 *
 */
@Repository("requireDao")
public interface RequireDao {
    /**
     * 获取索引文档的信息
     * @return
     */
public List<Require> getAllNeed();
/**
 * 获取附近的订单用户
 * @return
 */
public List<UserEntity> getAllUser();
}

@Repository(value="requireDao")注解是告诉Spring,让Spring创建一个名字叫“requireDao”的requireDaoImpl实例。 当Service需要使用Spring创建的名字叫“requireDao”的requireDaoImpl实例时,就可以使用@Resource(name = "requireDao")注解告诉Spring,Spring把创建好的requireDao注入给Service即可

 5. Spring中为了减少xml中配置,可以生命一个配置类(例如SpringConfig)来对bean进行配置。

//@Configuration
public class Connection {
    
//      此种通过spring方法容易出现链接异常,抛出read time out 错误,而找不到任何的错误
//    public @Bean HttpClientConfig httpClientConfig() {  
//
//        String connectionUrl = "http://192.168.1.60:9200";  
//        String username="shanjin";
//        String passwd="shanjin";
////        try {
////            Properties prop = PropertiesLoaderUtils.loadAllProperties("elasticsearch.properties");
//////            connectionUrl = StringUtil.null2Str(prop.get("elasticsearch.address"));
////            if (connectionUrl==""){
////                connectionUrl="http://192.168.1.60:9200";
////            }
////            username = StringUtil.null2Str(prop.get("username"));
////            passwd = StringUtil.null2Str(prop.get("password"));
////
////        } catch (Exception e) {
////            System.out.println(e.getMessage());
////        }        
//        HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(connectionUrl).defaultCredentials(username, passwd)
//                .connTimeout(Integer.MAX_VALUE)
//                .readTimeout(Integer.MAX_VALUE).multiThreaded(true).build();  
//        return httpClientConfig;  
//    } 

原文地址:https://www.cnblogs.com/youran-he/p/7451537.html