0

I would like to pass string value "hello" from spring bean to java method

Below is my bean configuration:

<bean id="myProcessName" class="java.lang.String" >

<constructor-arg  value="hello"/>       

</bean>

Below java class with the method

import javax.annotation.Resource;

public class Process {

private String procName;

@Resource(name = "myProcessName")
public void setMyProcessName(String procName) {
    this.procName = procName;
}   

}
1
  • If i understand your question properly, You could easily do so by creating a bean id for the bean with value 'hello' and using its reference in method. Commented Dec 8, 2015 at 2:07

1 Answer 1

1

You cannot autowire primitives and Strings. Spring does not support it.

You can simply do this

<bean id="myProcessId" class="beans.Process">
    <property name="procName" value="hello"></property>
</bean>


        package beans;
        public class Process {
            String procName;

            public String getProcName() {
                return procName;
            }

            public void setProcName(String procName) {
                this.procName = procName;
            }
        }


        public class App {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            Process p = (Process) ctx.getBean("myProcessId");
            System.out.println(p.getProcName());//will print hello
        }

}
Sign up to request clarification or add additional context in comments.

2 Comments

That's not correct. You can easily autowire Strings as in the following example, where you inject the myProcessName bean (defined above): @Value(value="#{myProcessName}") private String procName;
or alternatively: @Autowired @Qualifier("myProcessName")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.