简体   繁体   English

如何使用@Component 和@Value 原型传递引用?

[英]How to pass reference using @Component and @Value stereotype?

Here below I added some classes, Student class depends on Address Class.下面我添加了一些类,学生 class 取决于地址 Class。 object of student class created how to add 'ad' value which is inside Address using @Component and @Value学生 class 的 object 创建了如何使用 @Component 和 @Value 添加位于地址内部的“广告”值

Student Class学生 Class

package com.spring.stereotype;
  import java.util.List;
  import org.springframework.beans.factory.annotation.Value;
  import org.springframework.stereotype.Component;
        
        @Component("obj")
        public class Student {
         
            private Address ad;
    
         public Address getAd() {
            return ad;
        }
        public void setAd(Address ad) {
            this.ad = ad;
        } 
        }

Address Class地址 Class

package com.spring.stereotype;
    
    public class Address {
      
        private String ad;
    
        public String getAd() {
            return ad;
        }
    
        public void setAd(String ad) {
            this.ad = ad;
        }
    
        @Override
        public String toString() {
            return "Address [ad=" + ad + "]";
        }   
    }

Main class主class

package com.spring.stereotype;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("com/spring/stereotype/stereo.xml");
        
        Student st = context.getBean("obj",Student.class);
    
        System.out.println(st.getAd());
    }

}

Is showing an error if I add an XML file, here I typed how I created the object <context:component-scan base-package="com.spring.stereotype"/>如果我添加 XML 文件,则会显示错误,在这里我输入了我如何创建 object <context:component-scan base-package="com.spring.stereotype"/>

I think that you're misunderstanding the use of packages in Spring and Java.我认为您对 Spring 和 Java 中的包的使用有误解。 The com.spring.stereotype package is an internal package from the Spring framework. The com.spring.stereotype package is an internal package from the Spring framework. You should never use such a package as a base one for your own project.您永远不应该使用这样的 package 作为您自己项目的基础。 Especially, when you're using classes from Spring and have this framework on your classpath.特别是,当您使用 Spring 中的类并在类路径中有此框架时。

Also, you shouldn't use XML for the application context configuration in 2022. It's been deprecated for years.此外,您不应在 2022 年将 XML 用于应用程序上下文配置。它已被弃用多年。 It might be used in legacy projects, but you shouldn't use it for learning projects and for creating new applications.它可能用于遗留项目,但您不应该将它用于学习项目和创建新应用程序。

What you should probably do:你可能应该做什么:

  1. Replace the com.spring.stereotype package with your own one.用您自己的替换com.spring.stereotype package。 For example, com.example .例如, com.example
  2. Read about Spring Boot and how it can be used for configuring the application context.阅读有关Spring 引导以及如何使用它来配置应用程序上下文的信息。 You will a few tutorials by following the specified link.您将按照指定的链接学习一些教程。

Working application example for your case:适用于您的案例的工作应用程序示例:

The pom.xml file: pom.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demotest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demotest</name>
    <description>demotest</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The Student bean. Student豆。 I've also added the @PostConstruct method to assign a test address:我还添加了@PostConstruct方法来分配测试地址:

package com.example.demotest;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component("student")
public class Student {

    @PostConstruct
    public void init() {
        this.setAd("test");
    }

    private String ad;

    public String getAd() {
        return ad;
    }

    public void setAd(String ad) {
        this.ad = ad;
    }

    @Override
    public String toString() {
        return "Address [ad=" + ad + "]";
    }
}

The main class:主要class:

package com.example.demotest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemotestApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemotestApplication.class, args);
        Student st = context.getBean("student", Student.class);
        System.out.printf("\nStudent address: %s", st.getAd());
    }
}

Application run logs:应用程序运行日志:


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.3)

2022-09-08 22:33:59.954  INFO 44414 --- [           main] c.example.demotest.DemotestApplication   : Starting DemotestApplication using Java 17.0.2
2022-09-08 22:33:59.955  INFO 44414 --- [           main] c.example.demotest.DemotestApplication   : No active profile set, falling back to 1 default profile: "default"
2022-09-08 22:34:00.205  INFO 44414 --- [           main] c.example.demotest.DemotestApplication   : Started DemotestApplication in 0.382 seconds (JVM running for 0.605)

Student address: test
Process finished with exit code 0

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

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