spring 中bean学习笔记

spring 中bean

一、bean的定义和应用

1、 bean 形象上类似于getXX()和setXX()的一种。

2、 由于java是面向对象的,类的方法和属性在使用中需要实例化。

3、 规律:凡是子类及带有方法或者属性的类都要加上注册bean。

4、 bean类似于类的代理人.

5、 带有@的字符,spring都会自动扫描一下,看一下是啥。

二、 注解

1、 xml配置文件中自带的bean。@autowired @resource,在spring中通过byType和ByName来使用

2、注册bean。 在@component、@Control、@Service、@Configuration、@Repository中,这些注解会把你要实例化的对象化成一个bean。

三、 例子

@Configuration

public class Connection {

 

    public @Bean HttpClientConfig httpClientConfig() { 

        String connectionUrl = "http://192.168.1.13:9200"; 

        HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(connectionUrl).multiThreaded(true).build(); 

        return httpClientConfig; 

    } 

   @Bean(name="jestClient")

    public synchronized static JestClient jestClient() { 

        JestClientFactory factory = new JestClientFactory(); 

         

        return factory.getObject(); 

    } 

}

@Configuration中已经注册了bean,在方法中加入了@bean方法,我在另外一个类的引用的时候如下:

   @Autowired

    private JestClient jestClient;

此句的生命在spring中扫描的时候会自动初始化jestclient这个对象,并给此对象赋值。

这个是我学习spring mvc做的笔记,记录一下!

posted @ 2017-08-16 09:42  李悠然  阅读(202)  评论(0编辑  收藏  举报