springspring-bootspring-mvcstereotype

How to pass reference using @Component and @Value stereotype?


Here below I added some classes, Student class depends on Address Class. object of student class created how to add 'ad' value which is inside Address using @Component and @Value

Student 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

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

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"/>


Solution

  • I think that you're misunderstanding the use of packages in Spring and Java. 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. Especially, when you're using classes from Spring and have this framework on your classpath.

    Also, you shouldn't use XML for the application context configuration in 2022. It's been deprecated for years. 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. For example, com.example.
    2. Read about Spring Boot and how it can be used for configuring the application context. You will a few tutorials by following the specified link.

    Working application example for your case:

    The pom.xml file:

    <?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. I've also added the @PostConstruct method to assign a test address:

    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:

    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