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"/>
I think that you're misunderstanding the use of packages in Spring and Java. The
com.spring.stereotypepackage 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:
com.spring.stereotypepackage with your own one. For example,com.example.Working application example for your case:
The pom.xml file:
The
Studentbean. I've also added the@PostConstructmethod to assign a test address:The main class:
Application run logs: