1

I use javax standard annotation @Named for defining beans in spring4. To set the bean name I could tried @Named("MyBean") but it did not change the bean name.

I used spring Component annotation @Component("MyBean") and it worked fine.

Is it possible to set the bean name by using @Named

The bean is defined asL

@Named("myBean") //This not
@Component("myBean") //This works
@Scope("session")
public class User implements HttpSessionBindingListener, Serializable {

The application.context is

<context:component-scan base-package="foo.bar" />
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173

1 Answers1

2

I agree to what @fabian has said. You can use @Named annotation to set the bean name. If bean name doesn't matches, it falls back to auto-wiring by type.

I tried couple of examples. They worked for me.

AppConfig.java

package com.named;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class AppConfig {

}

NamedService.java

package com.named;

import javax.inject.Named;

@Named("namedTestDependency")
public class NamedService {

    public void namedMethod(){
        System.out.println("Named method");
    }

}

NamedServiceTest.java

package com.named;

import static org.junit.Assert.assertNotNull;

import com.named.AppConfig;
import com.named.NamedService;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
public class NamedServiceTest {

    //Matched by name of dependency
    @Autowired
    private NamedService namedTestDependency;

    //Falls back to auto-wiring by type
    @Autowired
    private NamedService noDeclaration;

    @Test
    public void testAutowiring(){
        assertNotNull(namedTestDependency);
        assertNotNull(noDeclaration);
    }

}
asg
  • 2,248
  • 3
  • 18
  • 26