简体   繁体   English

使用弹簧注解创建对象

[英]Creating object using spring annotations

I am beginner to spring.我是春天的初学者。 I have gone through some online tutorials and written a simple program, but I couldn't understand the worth.我浏览了一些在线教程并编写了一个简单的程序,但我无法理解其价值。 When we use spring.xml file and we create object with getBean method.当我们使用 spring.xml 文件并使用 getBean 方法创建对象时。 But, in case of annotations I am creating the object using new, which I think is not right.但是,在注释的情况下,我使用 new 创建对象,我认为这是不对的。 Please see below the code and let me know if the procedure i have followed is problematic or not.请查看下面的代码,让我知道我遵循的程序是否有问题。

Hello.java:

package bean;

import org.springframework.stereotype.Component;

@Component
public class Hello {

    String gender;

    public void print(){
        System.out.println("Hello world "+gender);
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

AppConfig.java:

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import bean.Hello;

@Configuration
public class AppConfig {

    @Bean(name="h")
    public Hello getHello(){
        Hello h= new Hello();
        h.setGender("male");
        return h;
    }

}

Driver.java:

package client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import bean.Hello;
import config.AppConfig;

public class Driver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);

        Hello h=ct.getBean("h",Hello.class);

        h.print();

    }

}

As you can see in AppConfig.java, I am creating the object of my class using正如您在 AppConfig.java 中看到的,我正在使用

Hello h= new Hello();

This looks problematic.这看起来有问题。 If i have to create object by myself, then why do we need spring.如果我必须自己创建对象,那为什么我们需要 spring。 Please suggest what I am doing wrong here.请建议我在这里做错了什么。

Edit when you use @Component("h") , you are creating a bean with name h with certain properties defined in Hello class. 使用@Component("h")时进行编辑 ,这将创建一个名称为h的bean,并具有Hello类中定义的某些属性。 So you don't need Appconfig class. 因此,您不需要Appconfig类。 And also you should not try to change beans properties (like setGender) elsewhere except in Hello class. 同样,除了Hello类之外,您也不应尝试在其他地方更改bean属性(例如setGender)。 So when should i use config class? 那么我什么时候应该使用config类呢? When you dont mark Hello class as bean(ie dont use component annotation). 当您不将Hello类标记为bean时(即,不使用组件注释)。 You create a Hello class object, set certain properties and mark it as a bean(using @bean). 您创建一个Hello类对象,设置某些属性并将其标记为bean(使用@bean)。

No you don't have to create object by yourself. 不,您不必自己创建对象。 Mark Hello class as @Component("h") and you can get the bean directly using Hello h=ct.getBean("h",Hello.class); 将Hello类标记为@Component("h") ,您可以使用Hello h=ct.getBean("h",Hello.class);直接获取Bean Hello h=ct.getBean("h",Hello.class); .

You can also use Autowired annotation to get your bean anywhere and do whatever you want to. 您还可以使用自动装配注释将bean放置在任何地方,并做您想做的任何事情。

Thera are 2 ways to be able to create a bean inside Spring Context Thera是在Spring Context中能够创建bean的2种方法

  1. Using @Component annotation (delegate creation Spring Framework ) 使用@Component注释(委托创建Spring Framework)

@Component : annotation above a class indicates that this class is a component and should be automatically detected and instantiated. @Component :类上方的注释表示该类是组件,应被自动检测和实例化。 Thus a Spring component bean will look like : 因此,Spring组件bean将如下所示:

@Component
public class User {
  private String name;

  private String address;

  public String getName() {
return name;
  }

  public void setName(String name) {
this.name = name;
  }

  public String getAddress() {
return address;
  }

  public void setAddress(String address) {
this.address = address;
  }
}

Scan your beans with component scan: 使用组件扫描来扫描您的bean:

Xml old school Spring configuration: Xml老派Spring配置:

  <context:component-scan base-package=”com.yourpackage” />

Component scan (If you use Spring boot it will be included inside @SpringBootAppilcation) 组件扫描(如果使用Spring boot,它将包含在@SpringBootAppilcation中)

@ComponentScan(basePackageClasses = Yourclass.class)
  1. Using @Configuration annotation: (your actual choose) 使用@Configuration批注:(您的实际选择)

Using @Configuration class with a method annotated with @bean. 将@Configuration类与@bean注释的方法一起使用。 You should provide here how to create new object setting values (your getHello method): 您应该在此处提供如何创建新的对象设置值(您的getHello方法):

 @Bean(name="h")
public Hello getHello(){
    Hello h= new Hello();
    h.setGender("male");
    return h;
}

You don't require to create bean explicitly in AppConfig.java class as you already have @Component annotation on Hello.java class. 您不需要在AppConfig.java类中显式创建bean,因为Hello.java类上已经具有@Component批注。 It will automatically create bean. 它将自动创建bean。

You can directly access the bean with your code in main but you need to specify name of bean in @Component as "h". 您可以使用main中的代码直接访问Bean,但需要在@Component中将Bean名称指定为“ h”。

 ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);

        Hello h=ct.getBean("h",Hello.class);

        h.print();

You just need to use Autowired and have a getter 您只需要使用自动Autowired并获得getter

@Autowired
private Hello hello;

public Hello getHello () {return hello;}

Answering this question as there is no accepted answer.回答这个问题,因为没有公认的答案。 So, what you have done is one way of asking SpringContainer to create bean and that can be used in other places.所以,你所做的是一种让 SpringContainer 创建 bean 的方法,它可以在其他地方使用。

Basically, we can ask spring to create object for us using three types.基本上,我们可以让 spring 使用三种类型为我们创建对象。

  1. XML-based Configuration,基于 XML 的配置,
  2. Annotation-based Configuration,基于注解的配置,
  3. Java-basedConfiguration.基于Java的配置。

You have used Java-based configuration.您已经使用了基于 Java 的配置。 Its not like we should not use "new" keyword to create object when using spring framework.它不像我们在使用 spring 框架时不应该使用“new”关键字来创建对象。 It is kind of useful at some scenarios like creating object of DataSource(providing database details).它在某些情况下很有用,例如创建 DataSource 对象(提供数据库详细信息)。

So, if you want spring to create object for you along with object properties, we can make use of @component and @value annotation.因此,如果您希望 spring 为您创建对象以及对象属性,我们可以使用 @component 和 @value 注释。 Refer code below,参考下面的代码,

package com.vj.spring.springanno;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Hello {

    @Value("dummy value")
    String gender;

    
    public void print(){
        System.out.println("Hello world "+gender);
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

Your Appconfig class should look like this(read comments as well),您的 Appconfig 类应如下所示(也请阅读评论),

package com.vj.spring.springanno;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration // makes this class similar to spring.xml(old school way)
@ComponentScan("com.vj.spring") // replacement of <context:component-scan base-package=”com.yourpackage” /> in spring.xml
public class AppConfig {


    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Hello hello = context.getBean(Hello.class); // or context.getBean("hello",Hello.class);
        hello.print();

    }
}

By default, if use @component annotation, it creates reference name like "hello" (camelCase of Class name).默认情况下,如果使用@component 注解,它会创建像“hello”这样的引用名称(类名称的驼峰式)。 If you would want so specify reference name, you could do like @component("h").如果您希望如此指定引用名称,您可以像@component("h") 那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM