Home > AI > Backend > SpringBoot >

@Resource

Tell you which Bean to inject.

Example: codes

Employee.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company {
    private String name;
    private String location;
}

Company.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company {
    private String name;
    private String location;
}

resource-annotation.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- To activate the '@Resource' annotation in the spring framework -->
    <context:annotation-config />

    <bean id="mycompany" class="com.example.demo.redis.Company">
        <property name="name" value="Test Pvt. Ltd." />
        <property name="location" value="India" />
    </bean>

    <bean id="myemployee" class="com.example.demo.redis.Employee">
        <property name="id" value="123456" />
        <property name="name" value="Charlotte O' Neil" />
    </bean>
</beans>

DemoApplication.java


@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("resource-annotation.xml");
        Employee emp = ac.getBean("myemployee", Employee.class);
        System.out.println(emp.toString());

	}
}

Leave a Reply